How to provide a default model object for relationships?

Laravel: How to provide a default model object for relationships?

If you have a relationship (such as a belongsTo()) relationship, it might not always return a result.

This will then mean that every time you do something like this:

  1. $post = Post::first();
  2. $author = $post->author; // what if the relationship in author() returns nothing?
  3. echo $author->name; // $author might have been null, so this will cause an error

There are three main options to handling this:

1) wrap everything in optional() (which will let you do anything to that variable and it will return null if there was nothing set).

2) Wrap everything in if ($author) { ... } to make sure $author isn't a null value

3) or set a default model. If nothing is found for a relationship then it will create an empty object (of the same type as the relationship defines - in the case below it will be \App\User).

  1. /**
  2.  * Get the author of the post.
  3.  */
  4. public function user()
  5. {
  6.     return $this->belongsTo('App\User')->withDefault();
  7. }
  8.  
  9. // you can also define some defaults for the default!
  10.  
  11. /**
  12.  * Get the author of the post.
  13.  */
  14. public function user()
  15. {
  16.     return $this->belongsTo('App\User')->withDefault([
  17.         'name' => 'Guest Author',
  18.     ]);
  19. }
  20.  
  21. /**
  22.  * Get the author of the post.
  23.  */
  24. public function user()
  25. {
  26.     return $this->belongsTo('App\User')->withDefault(function ($user) {
  27.         $user->name = 'Guest Author';
  28.     });
  29. }

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 provide a default model object for relationships?

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

How can you check if a variable is alphanum (alphanumeric, letters and numbers only) in PHP?

How to get table column names from a database table in Eloquent?

How to block an IP range based on CIDR in Apache with .htaccess

How to find out which php.ini file PHP is using?

Force trailing slash (redirect if no trailing slash exists) in .htaccess

What are PHP's PSRs?

How to set up an alias to map one directory to another destination

How to block IPv6 IP addresses in .htaccess

How to see all of the options for an artisan command?

What are the SPL Iterators in PHP?