Trying to get property of non-object?

1

This is my View :

<tbody>
    @if(isset($pessoas))
        @foreach($pessoas as $p)
            <tr>
                <td>{{$p->nome}}</td>
                <td>{{$p->idade}}</td>
                <td>{{$p->cidade->nome}}</td>
        @endforeach
    @endif
</tbody>

The% w /% passing the people parameter and returns Controller :

public function verPessoas()
{      
    $pessoas = Pessoa::all();
    return view('verPessoas', compact('pessoas'));
}

Link in View Model

public function cidade()
{
    return $this->belongsTo('App\Cidade');
}

Relationship in Model "City"

public function pessoa()
{
    return $this->hasMany('App\Pessoa');
}

This relationship is 1: N , where the Pessoa table receives the foreign key of pessoas ( cidade ), being a city has several people, each person belongs to a city . When I try to access this cidade_id I get error :

  

View

When I remove the line

<td>{{$p->cidade->nome}}</td>

Everything works normally, leading me to believe that I am relating Trying to get property of non-object (View: C:\xampp\htdocs\projetos\PROJETO\resources\views\verPessoas.blade.php) in the wrong way and checked the bank tables and their values, everything is filled and working perfectly.

I would like to understand what causes this error and what is the appropriate solution.

    
asked by anonymous 02.03.2017 / 14:40

2 answers

1

If your relationships are correct, do so:

With with :

public function verPessoas()
{      
    $pessoas = Pessoa::with('cidade')->get()
    return view('verPessoas', compact('pessoas'));
}
A reason in which this is the recommended way : in this case it runs two SQL and the logic of the algorithm makes the inclusion of the items in its this destination has a great differential in the application performance, since since otherwise each interaction of for is made a new SQL degrading the application a lot

02.03.2017 / 20:54
2

In your relation to the other model put the attribute that makes the link (foreign key) as the second parameter, this may be because eloquent needs to know which parameter to use in the query if the name of the your foreign key is not in the (table_name) _id.

In Person:

public function cidade(){
    return $this->belongsTo(Cidade::class, 'cidade_id');
}

In City:

public function pessoa(){
    return $this->hasMany(Pessoa::class, 'cidade_id');
}
    
02.03.2017 / 15:23