php - Default User model and Relatinship - Laravel 5.4 -


i use default user model , have created userstatus model:

user

class user extends authenticatable  { use notifiable;  /**  * attributes mass assignable.  *  * @var array  */ protected $fillable = [     'name', 'email', 'password', ];  /**  * attributes should hidden arrays.  *  * @var array  */ protected $hidden = [     'password', 'remember_token', ];  public function status() {     return $this->belongsto('app\userstatus'); } 

}

userstatus

namespace app;  use illuminate\database\eloquent\model;  class userstatus extends model { public $timestamps = false;  public function users() {     return $this->hasmany('app\user'); } } 

i cant access related model attribute because $user->status null:

$users = user::all();  foreach ($users $user) {     var_dump($user->status->name); } 

what best practice/solution?

thanks!

your query cause n+1 query problem.

try efficient

$users = user::with('status')->get();  foreach ($users $user) {    logger($user->status->name); } 

Comments

Popular posts from this blog

'hasOwnProperty' in javascript -

python - ValueError: No axis named 1 for object type <class 'pandas.core.series.Series'> -

java - How to provide dependency injections in Eclipse RCP 3.x? -