简体   繁体   中英

Call to a member function all() on null

I had relationship made that is User and UserDetail.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $table ='users';

    protected $fillable = ['name', 'email', 'password'];

    public function user(){
        return $this->hasOne('App\UserDetail');
    }
}

UserDetail.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class UserDetail extends Model
{
    protected $table ='user_details';

    protected $fillable = ['user_id', 'address', 'gender'];

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

but when I call it in the controller

  public function showUserInformation($id){
    $details= $this->user->detail;
    dd($details);
  }

it returns null when I dd it. why was it happening? Kindly help me please

Try (in your User.php)

public function detail(){
        return $this->hasOne('App\UserDetail');
    }

change user() to detail()

You have to declare the id is a User model. Change you function to this:

     public function showUserInformation(User $id){
         $details= $id->user->gender;  
         dd($details);
  }

I think you are misunderstanding the '$this' keyword.

In your controller you have this piece of code:

  public function showUserInformation($id){
    $details= $this->user->detail;
    dd($details);
  }

in this code sample, $this points to the controller. So basically you're asking 'give me the user variable from this controller and get the details from it'. But does the controller has a user variable? (I'm guessing no since you're getting null errors).

You can just grab the model directly like so:

  public function showUserInformation($id){
    $details= UserDetail::whereUserId($id)->first();
    dd($details);
  }

Yeah i managed to get the data but not through eloquent. I did traditional query. Thanks to all your help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM