Jonio
Jonio

Reputation: 1293

laravel 5.5 model relation in json

I'm trying to understand, if in laravel 5.5 there is a method that given a model linked to another with an external key, I can obtain the result of the complete join of the attributes of both models. I wanto to avoid to return two models and merge them.

Below the code of my model:

class Event extends Model { 
     public function location(){
         return $this->hasOne('App\Location');
     }
 }

In the controller I obtain the location information of the respective Event, but in the result I would like to see information of both Event and Location.

In the controller If I call the model with the ORM:

  $event = Event::where('name',$name)->first()->location;

  $model=$eventLocation->getModel();
   return $model;

And obtain this json with

{"id":12,"created_at":null,"updated_at":null,"name":"location_test","event_id":"1"}

That contains only the attributes of the location and not for the Event! How can I show both?

thanks

Upvotes: 0

Views: 976

Answers (3)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111899

You can use:

$event = Event::with('location')->where('name',$name)->first();

or:

$event = Event::where('name',$name)->first();
$event->load('location');

Then when you just return model or call $event->toJson() you will have your location relationship loaded.

If you want to get details about loading relationships you can look at laravel eager loading using with() vs load() after creating the parent model

Upvotes: 0

Mathieu Ferre
Mathieu Ferre

Reputation: 4422

Try this :

$event = Event::with('location')->where('name', $name)->first();

return $event->toJson();

You will have access to your event with data.location

Upvotes: 0

Sniper Wolf
Sniper Wolf

Reputation: 471

Try with:

$event = Event::with('location')->where('name', $name)->first();
$location = $event->location;

In this way you will get the event itself and the complete related location as location field.

See the Eager Loading section on the docs.

Upvotes: 1

Related Questions