Laravel Eloquent, return JSON with the "ownTo" object?

I have two models with a one-to-many relationship.

class User extends ConfideUser { public function shouts() { return $this->hasMany('Shout'); } } class Shout extends Eloquent { public function users() { return $this->belongsTo('User'); } } 

Everything seems to be working fine. BUT, How do I get this to return a user object nested in scream objects? Now it returns only all my screams, but I do not have JSON access to the owned user model.

 Route::get('api/shout', function() { return Shout::with('users')->get(); }); 

This simply returns this JSON with no user object for each call:

 [{"id":"1","user_id":"1","message":"A little test shout!","location":"K","created_at":"2013-05-23 19:51:44","updated_at":"2013-05-23 19:51:44"},{"id":"2","user_id":"1","message":"And here is an other shout that is a little bit longer...","location":"S","created_at":"2013-05-23 19:51:44","updated_at":"2013-05-23 19:51:44"}] 
+4
source share
4 answers

I get it.

When working with the "belongs" relation, you need to call user () not users () for this method.

Has the meaning.

And it seems to work.

+2
source

I had the same problem using Laravel 5. I just wanted to add that I got it to work using the Model::with("relationship")->get() method on the model.

+4
source

If you use:

 protected $visible = ['user']; 

Remember to add relationships there to be visible in JSON

+1
source

u can use protected $with = ['users']; in Class Shout and use protected $with = ['shouts']; .

and Give the full namespace model name

 class Shout extends Eloquent { protected $with = ['users']; public function users() { return $this->belongsTo('App\User'); } } 

and

 class User extends ConfideUser { protected $with = ['shouts']; public function shouts() { return $this->hasMany('App\Shout'); } } 

Receive

 Route::get('api/shout', function() { return Shout::all()->toJson; }); 
0
source

Source: https://habr.com/ru/post/1482608/


All Articles