Cannot fetch eloquent model data

Posted 10 months ago by ravipw1801

One to Many relation: A country has many cities & a city belongs to one country.

Country model:

<?php    
namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Database\Eloquent\Relations\Relation;
    
    
    class Country extends Model
    {
        protected $fillable = ['name'];
    public function cities()
        {
            return $this->hasMany('App\City');
        }
    }

City Model:

<?php    
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Database\Eloquent\Relations\Relation;
    
    
    class City extends Model
    {
        protected $fillable = ['name'];
    public function country()
        {
            return $this->belongsTo('App\Country','country_id');
        }
    }

View blade file:

@foreach($cities as $city)
        {{$city->name}} - {{$city->country}}<br>        
@endforeach 

Result

Mumbai - {"id":2,"name":"India","created_at":"2018-06-25 14:22:54","updated_at":"2018-07-05 
14:33:17"}
Pointe-Nore - {"id":2,"name":"Rep. of Congo","created_at":"2018-06-25 
14:22:54","updated_at":"2018-07-05 14:33:17"}
Keqiao - {"id":2,"name":"China","created_at":"2018-06-25 14:22:54","updated_at":"2018-07-05 
14:33:17"}

& When I put the following in the blade file

@foreach($cities as $city)
        {{$city->name}} - {{$city->country->name}}<br>      
@endforeach 

I get error as

ErrorException (E_ERROR)
Trying to get property 'name' of non-object

When I try to fetch the same thing in tinker, everything works fine!

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.