mercredi 30 mai 2018

When a Parent has no child in a one to many relationship I get a non-object error when checking it

I have a 'Parent' Table (server) and a 'Child' Table (Server Status) the server status is connected to the server table via its id e.g. the servers id is the same as the server_id in the server status migration using a one to many relationship. What I am trying to do then is iterate through my list of servers and then display the status of the server, which is stores in the server status table. For some reason I am getting non-object error when trying to iterate through a server that has no status. This works then a server has a status that is corresponding to it but but not when I have only a server and no status. Can anyone give me some insight on to why this may be happening? Here is the current code for the controller calling this view, and the loop used to iterate through the data.

index.blade.php:

@guest  
 @if(count($servers) > 0)
   @foreach($servers as $server)
     @if($server->isPublic === 1 )
        @include('inc.statuses')
     @endif
   @endforeach
 @endif
@endguest

@auth
 @if(count($servers) > 0)
   @foreach($servers as $server)
     @include('inc.statuses') 
   @endforeach
 @endif
@endauth

statuses.blade.php:

@if($server->serverStatus->last()->status_id === 1)
    <a href="/servers/"  class="text-dark list-group-item list-group-item-success"></a>
@elseif($server->serverStatus->last()->status_id === 2)
    <a href="/servers/" class="text-dark list-group-item list-group-item-warning" ></a>
@elseif($server->serverStatus->last()->status_id === 3)
    <a href="/servers/" class="text-dark list-group-item list-group-item-danger" ></a>
@elseif($server->serverStatus->last()->status_id === 4)
    <a href="/servers/" class="text-dark list-group-item list-group-item-warning" > is under maintinance</a>
@elseif($server->serverStatus->last()->status_id === null)
    <a href="/servers/" class="text-dark list-group-item list-group-item-warning" > has no inputted staus</a>
@else
    <a href="/servers/" class="text-dark list-group-item list-group-item-warning" > has no inputted staus</a>
@endif

controller:

public function index(){
        $servers = Server::orderBY('created_at', 'desc')->get();

        // foreach($servers as $server){
        //     var_dump($server->name);
        //     var_dump($server->serverStatus->last()->status_id);
        //     var_dump($server->serverStatus->last()->server_id);
        // }

        $incidents = Incident::orderBY('created_at', 'desc')->paginate(10);

        return view('pages.index', ['incidents' => $incidents, 'servers' => $servers]);
    }



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2sqQien
via IFTTT

Aucun commentaire:

Enregistrer un commentaire