0

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

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
Jonio
  • 1,213
  • 2
  • 15
  • 35

3 Answers3

1

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.

Sniper Wolf
  • 471
  • 2
  • 8
  • 19
  • I obtain only the informations about location, nothings about the Event... – Jonio Dec 22 '17 at 15:39
  • The event is inside `$event` variable you have a property `location` to access it. You can read all things using [`Collection`](https://laravel.com/docs/5.5/collections) methods like `toJson` or `toArray` on `$event` collection, like `$event->toJson()`. – Sniper Wolf Dec 22 '17 at 15:58
0

Try this :

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

return $event->toJson();

You will have access to your event with data.location

Mathieu Ferre
  • 4,246
  • 1
  • 14
  • 31
0

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

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291