Вызов методов в представлениях, определенных в модели. не работает - PullRequest
0 голосов
/ 29 апреля 2018

У меня было много моей логики во взглядах. Я реорганизовал это в методы в одной из моих моделей. Они распознаются, но на самом деле не работают, так как IF не изменяется при изменении базы данных, отражая другой метод, который должен быть вызван.

Например, мой код изначально был таким, со всей логикой в ​​представлениях.

@if($tenancy == null || $tenancy->accepted == 0 && $tenancy->request_sent != 1)
              <a href="/account/tenancy/{{$user->id}}/create" class="btn btn-primary">Start Tenancy</a>
            @endif


          <!-- 
            If the user signed in isn't the owner of this profile.
            Do not show these buttons that control accept/reject/end
          -->

        @if(Auth::user()->id == $user->id)
          <!-- 
            If the request has been sent but hasn't been accepted.
            Give the option to accept and reject.
            This updates the values in DB.
          -->
          @if($tenancy != null && $tenancy->accepted == 0 && $tenancy->request_sent == 1)
            <form method="POST" action="/account/tenancy/{{$user->id}}/accept">
              {{ csrf_field() }}
              <input type="submit" class="btn btn-primary" value="Accept Request">
            </form>
            <form method="POST" action="/account/tenancy/{{$user->id}}/reject">
              {{ csrf_field() }}
              <input type="submit" class="btn btn-warning" value="Reject Request">
            </form>
              <!-- 
                If the request has been accepted.
                Show button to end the tenancy,
                and property details
              -->
          @elseif($tenancy != null && $tenancy->accepted == 1 && $tenancy->request_sent == 0)
            <form method="POST" action="/account/tenancy/{{$user->id}}/end">
              {{ csrf_field() }}
              <input type="submit" class="btn btn-primary" value="End Tenancy">
            </form>
            <h5>Currently in Tenancy with {{$tenancy->landlord_name}}</h5>
            <h5>Your property is {{$tenancy->property_address}}</h5>
          @endif <!-- End of current user vs this user-->
        @endif <!-- Initial If-->

Затем я реорганизовал его, используя имена методов вместо logc. Методы определены в моем контроллере Tenancy.

@if(Auth::user()->id == $tenancy->tenant_id)
          <h1>You cannot add yourself</h1>
        @elseif($Tenancy->addTenancy())
          <a href="/account/tenancy/{{$user->id}}/create" class="btn btn-primary">Start Tenancy</a>

    @endif

      <!-- 
        If the user signed in isn't the owner of this profile.
        Do not show these buttons that control accept/reject/end
      -->

    @if(Auth::user()->id == $user->id)
      <!-- 
        If the request has been sent but hasn't been accepted.
        Give the option to accept and reject.
        This updates the values in DB.
      -->
      @if($Tenancy->hasRequestPending())
        <form method="POST" action="/account/tenancy/{{$user->id}}/accept">
          {{ csrf_field() }}
          <input type="submit" class="btn btn-primary" value="Accept Request">
        </form>
        <form method="POST" action="/account/tenancy/{{$user->id}}/reject">
          {{ csrf_field() }}
          <input type="submit" class="btn btn-warning" value="Reject Request">
        </form>
          <!-- 
            If the request has been accepted.
            Show button to end the tenancy,
            and property details
          -->
      @elseif($Tenancy->inTenancy())
        <form method="POST" action="/account/tenancy/{{$user->id}}/end">
          {{ csrf_field() }}
          <input type="submit" class="btn btn-primary" value="End Tenancy">
        </form>
        <h5>Currently in Tenancy with {{$Tenancy->landlord_name}}</h5>
        <h5>Your property is {{$Tenancy->property_address}}</h5>
      @endif <!-- End of current user vs this user-->
    @endif <!-- Initial If-->

Это контроллер, который отображает вид выше

  public function index($id){

   $user = User::where('id', $id)->first();
   $users = Auth::user();
   $Tenancy = new Tenancy;
   $tenancy =  DB::table('tenancy')->first();

  return view('/pages/account/index', compact('user', 'users', 'Tenancy', 'tenancy'));
}

Это модель Tenancy, в которой определены методы.

public function addTenancy()
{
    return $this->accepted == 0 && $this->request_sent == 0;
}

public function hasRequestPending()
{
    return $this->accepted == 0 && $this->request_sent == 1;
}

public function inTenancy()
{
    return $this->accepted == 1 && $this->request_sent == 0;
}

Я не понимаю, почему вновь обновляемое представление не должно перемещаться через оператор IF при изменении базы данных. Есть идеи?

1 Ответ

0 голосов
/ 29 апреля 2018

Я думаю, что вы не получаете красноречивую модель из базы данных, а только получаете первую строку из таблицы 'Tenancy', вы должны сделать что-то вроде этого $book = App\Book::first();, но сначала вы должны подключить вашу модель к базе данных

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...