Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

crsc's avatar
Level 1

Relationship understanding problem

Hello,

I'm new in Laravel and try to understand relationships.

For learning purposes I created three tables in my database:

users (id, name) routes (id, user_id, location_id_a, location_id_b) locations (id, user_id, longitude, latitude)

Now I want to fetch all routes from the logged in user. Every route have two locations inside: location_id_a for the start location and location_id_b for the end location. Every route need to fetch both locations (longitude, latitude).

I have really no idea how to do the query with relationships to show following in blade:

@foreach route-name location_a name + (longitude, latitude) location_b name + (longitude, latitude) @endforeach

Thanks a lot and best regards, Christian

0 likes
2 replies
ftrillo's avatar

After creating the tables in your DB. The next step is defining the relationships in each model. Details here: https://laravel.com/docs/5.5/eloquent-relationships#defining-relationships.

If you're just learning Eloquent you should start with simpler relations, but here we go.

Looking at the tables it seems these are the relationships:

User: hasMany routes() and hasMany locations(). I don't know why the locations table has an user_id though.

Route: belongsTo user(), belongsTo locationA() and belongsTo locationB(). For locationA and locationB you'll have to define a custom foreign key in the relation method. It's all in the documentation.

Location: belongsTo user(), hasMany routeA() and hasMany routeB(). Again, routeA and routeB are relations to the same model, but with different foreign keys. You can name the methods however you want to make them make sense in your business logic.

After all the relations are defined, or at least the ones you need, you can get the routes of the authenticated user like this:

// The locations are eager loaded for performance
$userRoutes = Auth::user()->routes()->with('locationA', 'locationB')->get();

foreach ($userRoutes as $route) {
    $route; // the Route model
    $route->locationA // The Location model with id matching location_id_a
    $route->locationB // The Location model with id matching location_id_b
}
crsc's avatar
Level 1

Hi ftrillo,

thank you for your detailed help. Now it's more clear for me and after some testing and reading it works now. My own solution before was nearly the same like yours but my mistake was to set toMany in the Route model and belongsToMany in the Location model.

Thanks again and best regards, Christian

Please or to participate in this conversation.