Skip to content

Início / Optitravel / Models

with(array $relations)

The with() method is used to eagerly load relationships defined in the model, allowing you to access related data immediately after calling find() or other fetching methods.

This method loops through the provided relation names and executes any model methods matching those names. These methods should return a relationship (e.g., from hasOne() or hasMany()).

The results are stored internally and can be accessed as properties of the object (e.g., $model->relatedItems).

Parameters

  • array relations – A list of method names (as strings) that define relationships in the model class. Each method should return a relationship defined via hasOne() or hasMany().

Returns

Returns the current model object with the specified relationships loaded and stored as properties.

Example

use \App\Models\Template;

$template = new Template();

// Load the template with its related members
$template = $template->find($params['id'])->with(['members']);

foreach ($template->members as $member) {
    echo $member->username . "<br>";
}
use \App\Models\Profile;

$profile = (new Profile())->find(5)->with(['user']);

echo $profile->user->email;

Notes

  • Relationship methods must exist in the model and return valid results from hasOne() or hasMany().

  • The method does not support nested relationships (e.g., user.profile.company). Only top-level relations are supported.

  • If a given relation method does not exist in the model, it will be skipped silently.

Behavior

  • If the $relations array is empty, the method does nothing and simply returns the current object.

  • For each valid relation name:

  • If a method with the same name exists in the model, it will be executed.

  • The result will be stored in $this->relationships[$relation].

  • The value will be accessible via $this->$relation.

  • This approach avoids lazy loading and provides eager access to related data immediately after loading a model.


(Última atualização: 13/05/2025)