I have the association ads table with users how I can show the users data. It shows me error trying to get property of non object association.
Tables:
- ads
- users (default Laravel)
In User Model:
public function ads()
{
return $this->hasMany('App\Ad','user_id');
}
In Ad Model
public function user()
{
return $this->belongsTo('App\User');
}
in Routes
Route::get('/ads',function(){
$ads = Ad::get();
//print_r($ads);
foreach ($ads as $ad) {
echo $ad->user->name;// issue here
}
});
It prints this array when I print_r($ad->user)
;
App\User Object ( [fillable:protected] => Array ( [0] => name [1] => phone [2] => email [3] => password [4] => role ) [hidden:protected] => Array ( [0] => password [1] => remember_token ) [connection:protected] => [table:protected] => [primaryKey:protected] => id [perPage:protected] => 15 [incrementing] => 1 [timestamps] => 1 [attributes:protected] => Array ( [id] => 1 [name] => irfan [email] => [email protected] [phone] => 43434 [password] => $2y$10$dnUuC9yxQwSHcpWy1oZlpuxaU33eBz1VYCPFQgfJYtncDivmDfqym [role] => User [remember_token] => x3l3x1tkXUB3I7KiRggPRclnCR5JGnDLlzCxZxeAmfpGCYFR0ylSrKNwSSuy [created_at] => 2016-06-12 17:42:36 [updated_at] => 2016-06-22 03:26:28 ) [original:protected] => Array ( [id] => 1 [name] => irfan [email] => [email protected] [phone] => 43434 [password] => $2y$10$dnUuC9yxQwSHcpWy1oZlpuxaU33eBz1VYCPFQgfJYtncDivmDfqym [role] => User [remember_token] => x3l3x1tkXUB3I7KiRggPRclnCR5JGnDLlzCxZxeAmfpGCYFR0ylSrKNwSSuy [created_at] => 2016-06-12 17:42:36 [updated_at] => 2016-06-22 03:26:28 ) [relations:protected] => Array ( ) [visible:protected] => Array ( ) [appends:protected] => Array ( ) [guarded:protected] => Array ( [0] => * ) [dates:protected] => Array ( ) [dateFormat:protected] => [casts:protected] => Array ( ) [touches:protected] => Array ( ) [observables:protected] => Array ( ) [with:protected] => Array ( ) [morphClass:protected] => [exists] => 1 [wasRecentlyCreated] => )