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 to remove .php from the end of URLs with .htaccess

How to block IPv6 IP addresses in .htaccess

How to select all rows for a certain month (or day, year or time), using Eloquent

How to hide the server signature (hide Apache info) from HTTP headers with .htaccess

How to check if a string contains a certain substring?

How to split a string into an array, in JS

How to add and remove items to an array in JS?

What is Agile software development?

How to make multiple routes share the same URL structure or URL parameters

How to replace whitespace with a single space