Its been a while since I have worked on a Laravel project and cannot see why this issue is happening.
I have a 'vehicles' table and also a 'customers' table.
In the vehicles table there is a row with a fields 'customer_id' that has the value of 1. There is a also a customer in 'customers' table with the id of 1.
In my Vehicle model I have:
public function customer()
{
return $this->belongsTo('App\Customer');
}
But when returning the data from the query:
$vehicle = Vehicle::find($id);
dd($vehicle);
The relations array is blank.
Where my mistake on this one? No errors, just no data.
If you want to get a customer with the vehicle:
$vehicle = Vehicle::with('customer')->find($id);
https://laravel.com/docs/5.4/eloquent-relationships#eager-loading
Wouldn't it be better if you define you relations like, assuming this is a One-To-Many Relationship?
In the Vehicles Model:
public function customer()
{
return $this->belongsTo('App\Customer', 'id', 'customer_id');
}
In the Customers Model
public function vehicle()
{
return $this->hasOne('App\Vehicle', 'customer_id', 'id');
}
Then load whatever you need
$vehicle = Vehicle::find($id);
But the relationship will be loaded only when called:
$vehicle->customer;