How to check if a relation was loaded on an Eloquent model already?

Laravel: How to check if a relation was loaded on an Eloquent model already?

Checking if a relation was loaded (maybe by a with() function call when using the Eloquent query builder) is easy.

From inside your model

If you want to do this within your model, you can use $this->relationLoaded():

  1. // from inside your model:
  2. if ($this->relationLoaded("comments")) {
  3.         //..
  4. }
From outside of your model
  1. $user = User::first();
  2. //
  3. if ($user->relationLoaded("comments")) {
  4.   //
  5. }
webdevetc profile pic
webdevetc

I am a 29 year old backend web developer from London, mostly focusing on PHP and Laravel lately. This (webdevetc.com) is my blog where I write about some web development topics (PHP, Laravel, Javascript, and some server stuff). contact me here.



More...


Comments and discussion about How to check if a relation was loaded on an Eloquent model already?

Found this interesting? Maybe you want to read some more in this series?

Or see other topics in the Laravel language

Or see other languages/frameworks:
PHP Laravel Composer Apache CentOS and Linux Stuff WordPress General Webdev and Programming Stuff JavaScript
Or see random questions

What is the max size, by default, of GET variables?

How to return an item in Eloquent, or throw a ModelNotFoundException exception if it isn't found?

How to access the Laravel's route parameters outside of the controller?

How to show a specific view file for certain error codes?

How to redirect your website to a new domain/location in .htaccess

How to set the Expires header in .htaccess

How to change the order that migrations happen?

How to get the first row that matches some where queries, or create it if it doesn't exist (in Laravel's Eloquent)?

How to install and use optipng on Linux CentOS

How to provide a default model object for relationships?