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 set custom HTTP headers in Apache (by editing .htaccess)

How to check if a object has a static variable defined?

How to generate an array for a dropdown (with ['key' => 'value']) suitable for a dropdown, from a Laravel collection of Eloquent objects?

How do you run a PHP script from the command line?

How to add comments in PHP

How to exclude URLs from the Laravel CSRF protection?

Is multiple inheritance supported in PHP?

How to block IP addresses in Apache by using regular expressions (regex) in .htaccess

How to check if a (blade) view file exists

How to force gzip compression in Apache with .htaccess