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

What are the SPL data structures

How to make Apache force download of files (in .htaccess)

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

What are some ways you can log debug messages and data in JS?

How to force non www in htaccess

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

How to set up custom error pages in .htaccess for your Apache server (ErrorDocument)

How to set infinite execution time in a PHP script

How to set the Expires header in .htaccess

What is WordPress default Apache .htaccess rules?