Skip to content

Início / Optitravel / Models

relation(string $relation)

The relation() method provides a safe way to access preloaded relationship data defined via with(). It checks if the given relationship has been loaded and returns it if available.

This is particularly useful in cases where you want to conditionally display or process related data without risking access to undefined properties.

Parameters

  • string relation – The name of the relationship previously loaded using the with() method.

Returns

  • The related data (array or object) if the relationship was loaded using with().
  • null if the relationship was not loaded or does not exist.

Example

use \App\Models\Template;

$template = new Template();
$template = $template->find(1)->with(['members']);

$members = $template->relation('members');

if ($members) {
    foreach ($members as $member) {
        echo $member->name . "<br>";
    }
} else {
    echo "No members found.";
}

Notes

  • This method only works with relationships that have been preloaded using the with() method.

  • It avoids direct property access ($model->relationName) and helps prevent undefined property errors.

  • Ideal for use in view templates or API responses where the presence of related data must be validated first.

Behavior

  • If the specified relationship exists in $this->relationships, it is returned.

  • If the relationship is not found, the method returns null.

  • This method does not attempt to load the relationship dynamically — it only accesses what was already loaded via with().


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