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

javascript - Confirm a form & display message if form is valid with JQuery -

Retrieving ETA (estimated time of arrival) with Google Distance Matrix API and public transit as transport mode -

ionic framework - Meteor - Error: Failed to execute 'insertBefore' on 'Node' -