Problem in a foreach

3

I'm using Laravel 5.3 , and when doing a foreach in the view, it does not recognize as an object, but if I print only what is in the $user variable it prints a json object %.

Controller:

public function getAll()
{
    return view('user.index',
        [
            'data' => $this->user->all(),
            'nav' => $this->nav
        ]
    );
}

Blade:

@foreach($data as $user)
    <tr>
        <td class="text-center">{{$user->id}}</td>
        <td class="text-center"><a href="/users/detalhes/{{$user->id}}">{{$user->name}}</a></td>
        <td class="text-center">{{$user->email}}</td> //essa é a linha que acusa o erro
        <td class="text-center"><a href="/empresas/detalhes/{{$user->empresa->id}}">{{$user->empresa->razao_social}}</a></td>
    </tr>
@endforeach

Error:

  

ErrorException in bd796ee4ce7ef1a15a679338ab7787ec13bf0e7d.php line 34:   Trying to get property of non-object (View: C: \ dev \ commerce \ controlnet \ resources \ views \ user \ index.blade.php)

Has anyone managed to find the error?

    
asked by anonymous 08.11.2016 / 12:17

2 answers

1

I solved the problem, some users are without a company, so the company method that has a belongs_to with user sometimes returns empty, so the properties of empresa does not come.

I solved the following conditional in the view:

@if($user->empresa)
    <td class="text-center"><a href="/empresas/detalhes/{{$user->empresa->id}}">{{$user->empresa->razao_social}}</a></td>
@else
    <td class="text-center">
        <strong>Sem empresa</strong>
    </td>
@endif
    
08.11.2016 / 12:52
4

I know you already posted a response, but another legal solution in Laravel would be to use or in the desired expression:

{!! $user->empresa->razao_social or "Sem empresa" !!}
    
08.11.2016 / 13:31