Home > Back-end >  Select multiple tables in Laravel Eloquent Relationship
Select multiple tables in Laravel Eloquent Relationship

Time:11-02

I'm using Laravel 9. I have defined the relationships in the appropriate models.

1st Model - Client (all client-related information) Primary Key (ID)

class Client extends Model
{
    use HasFactory;

    public function appointments()
    {
        return $this->hasMany(Appointment::class, 'client_id');
    }

    public function vehicles()

    {
        return $this->hasMany(Vehicle::class, 'client_id');
    }
}

2nd Model - Appointments (appointment info only) Foreign Key (client_id)

class Appointment extends Model
{
    use HasFactory;

    public function client()
    {
        return $this->belongsTo(Client::class, 'client_id');
    }
 
}

3rd Model - Vehicles (vehicle info only) Foreign key (client_id)

class Vehicle extends Model
{
    use HasFactory;

    public function client()
    {
        return $this->belongsTo(Client::class, 'client_id');
    }
   
}

I'm trying to select all from the three tables where IDs match using a where clause.

Here's my eloquent query code

class DashboardController extends Controller
{
    public function __invoke()
    {
        $clients = Client::with(['appointments', 'vehicles'])
        ->where('default_location', 'MM Alencar')
        ->get()
        ->dd();

        // return view('dashboard', ['clients' => $clients]);
    }
}

The DD returns two client models.

array:2 [▼
  0 => App\Models\Client {#1253 ▶}
  1 => App\Models\Client {#1254 ▶}
]

Both models are identical. I don't see any appointment or vehicle data attached. Sorry for the edit; I don't think I was clear enough on the first post. I need to be able to loop through the query as it will return anyone whose appointment type = 'test'

CodePudding user response:

Looks like a typo problem on your issue because you have written with appointments, and on view, you are trying to return $client->appointment (without 's').

Besides this, also confirm what the relationship names on the model is it appointment or appointments, if it is appointments and holds the relation one to many on that case, $client->appointments->type will also return error because, here appointments will return collections, on that case you need to map the $client->appointments and fetch type of each collection

Update:

After your update on the question, I can confirm that it has one to many relationships. So to get an appointment with a particular client you could do as:

foreach($clients as $k => $v){
  $v->appointments->dd(); //here you will get the appointments in array/collection. then you have to loop it in foreach / map/ pluck according to your needs.

}
  • Related