Mohamed  Kira Mohamed Kira - 1 month ago 12
PHP Question

retrieve all records with laravel eloquent

I tried following the docs here but didn't get the desired result,
My tables looks like

users table

id (pk - int) | username,


tweets table

id (pk - int) | user_id (fk - int) | tweet(varchar)


User Model

public function tweets() {
return $this->hasMany('App\Tweet', 'user_id); // user_id is FK
}


Tweet Model

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


And on the controller side, I'am using eloquent to retrieve data. I have this method,

public function ajax($id) {
$data = User::with('tweets')->find($id)->tweets();
return $data;
}


I tried following the logic here but I'm getting the following error on the controller code:


Trying to get property of non-object

Answer

Why not simply do like:

$User = User::find($id);
$tweets = Tweet::whereUserId($id)->get(); // or ->paginate(20);
return compact('User', 'tweets');

p.s. I know about eager loading, but it does the same operation + it also does additional but unnecessary operation to join tweets collection to User object.

Comments