Dhruba Chakraborty
Dhruba Chakraborty

Reputation: 39

Laravel Join : Trying to get property of non-object

I am trying to join two table. But it is giving an error "Trying to get property of non-object"... This is code in view page:

Asked by {{$user->name}}

In my controller I have code like this.

$user = DB::table('users')
                   ->join('question', function ($join) {
             $join ->on('question.id', '=', 'users.id')
                   ->where('question.ques_id' , '=', '$id');
    })
                   ->get();

I tried to do it like laravel documentation. Bust why this problem is arising?

Upvotes: 2

Views: 957

Answers (3)

Paul Spiegel
Paul Spiegel

Reputation: 31812

You can use a simple join:

$user = DB::table('users')
    ->join('question', 'question.id', '=', 'users.id')
    ->where('question.ques_id' , '=', $id);
    ->first()
    ->get();

But if you want to keep things simple, you should propper define your entities (User and Question) with their relations:

Class Question extends Model
{
    protected $table = 'question';
    protected $primaryKey = 'ques_id';

    public function user()
    {
        return $this->belongsTo(User::class, 'id');
    }
}

And keep the controller code simple:

$user = Question::find($id)->user;

Note: You should give things proper names. When i see question.id i think it's the ID of the question (not user).

Upvotes: 1

Dhruba Chakraborty
Dhruba Chakraborty

Reputation: 39

I couldn't figure out the problem in join, did it in a alternative way.

 $question = DB::table('question')
                ->where('ques_id' , $id)
                ->first();
 $user = \App\User::find($question->id);

It was not satisfying but got the job done.

Upvotes: 1

Dinh Phong
Dinh Phong

Reputation: 596

join is name of method you should let it lower-case like Laravel Document (look at Advanced Join Statements)

$user = DB::table('users')
                   ->join('question', function ($join) {
              $join->on('question.id', '=', 'users.id')
                   ->where('question.ques_id' , '=', $id);
    })
                   ->get();

And btw $id is a variable you should leave it without ' ' or use " "

I think this work !

Upvotes: 3

Related Questions