Search code examples
phplaravellaravel-5laravel-5.3

After create - why does it not return relationship?


When creating an entry using create() - Why does it return a relationship of pilot_id table instead of just showing the value of pilot_id?

For example, in the repository class:

public function createFlight()
  $flight = App\Flight::create([
     'name' => 'Flight 10'
     'pilot_id' => 4
  ]);

  return $flight;
}

In the controller:

public function show()
{
   $data = $this->flight->createFlight();
   return $data
}

It would return json on the screen but it is not showing the relationship table (pilot) of pilot_id.


Solution

  • Try adding the following to your Flight model, like so. By default you need to tell Laravel to include any relationships.

    protected $with = ['pilot'];
    

    That will make it so everytime it includes the relationship. If this is not desirable, then you will want to load the relationships when you return the flight, like so.

    return $flight->load(['pilot']);