0

On query get the error with undefine method. Simply i want to get data from two tables query look linke

  public static function userDetail($id){


    $result = User::whereHas('user_details', function ($query) {
        $query->where('user_details.user_id',$id);
    })->first();


    return $result ;
}

Relationship

On Model User define relationship

public function userDetails()
{
   return $this->hasOne(UserDetails::class);
}

and in userDetails model

public function user()
    {
        return $this->belongsTo(User::class);
    }
2
  • 'user_details' should be userDetails in whereHas Commented Apr 23, 2018 at 5:32
  • You will also need to add use($id) here: function ($query) use ($id) Commented Apr 23, 2018 at 5:46

2 Answers 2

2

just change

public static function userDetail($id){


$result = User::whereHas('user_details', function ($query) use($id) {
    $query->where('user_id',$id);
})->first();


return $result ;

}

Sign up to request clarification or add additional context in comments.

3 Comments

` "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'userDetails.user_id' in 'where clause' (SQL: select * from users where exists (select * from user_details where users.id = user_details.user_id and userDetails.user_id = 2) limit 1)",`
This means user_id column in your userDetails table didn't exist.
if it works please accept the answer and upvote. @Javed
1

If you dont need to use static, you can use this $result value on userDetails

public function userDetail($id){

        $result = userDetails::where('user_id', '=', $id)->first();

        return $result ;
}

Then the result can get access to the user from the vale by using $value->user->{user property}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.