Skip to content
Advertisement

Always get related model of relationship model in Laravel Eloquent

I have three Eloquent Models:

Company, OrdersArea and Localization where a company has many orders areas and orders area always have one localization.

I need to getting the Orders Area model to always load with Localization

If I do that:

$company = auth()->user()->company;

I gets Company of logged user without OrdersArea and it’s ok.

and next I could do:

$company->ordersArea;

and then I have in $company related models – OrdersArea – but this models doesn’t have Localization in itself but I need to get this always.

And in this situation:

$ordersArea = OrdersArea::find($id);

I want to get also $odersArea with localization property ($ordersArea->localization) with model.

How to do that – loading/getting $ordersArea always with related localization?

Advertisement

Answer

To load the Localization with the ordersArea() relation, you can use Eager loading. You can read more about this in the documentation: Eager Loading.

Example

$company->ordersArea()
    ->with('localization')
    ->first();

Alternatively, you can add the protected $with = ['localization']; to your OrdersArea model. This will always load the localization with the OrdersArea. You should only use this if that relation is always required.

You can also retrieve the relation after the parent model has already been retrieved. This is called Lazy Eager Loading.

$ordersArea = OrdersArea::find($id);
$ordersArea->load('localization');

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement