New in Laravel 5.5

Let’s dive into the new Laravel 5.5 features that’ll be available when it’s released

  1. Exception helper functions

New to Laravel 5.5 are two exception helper functions and i know we do love helper functions. I thought to myself the first time i saw these functions whether we really need helper functions to throw exceptions based on a particular condition, but once i start using this, it actually made sense and cleaned up code.

Lets dive in

I will use an hypothetical case where we have a name method which returns the name of a user and i want to throw an exception if this doesn’t exist. The traditional way to do this is to is by an if statement if a condition isn’t met as shown below

User.php // user model
/**
* Get user name
* @return string
* @throws App\Exceptions\NoNameException
**/
public function name()
{
if ($this->name === null) {
throw new NoNameException;
}
   return $this->name;
}

// NoNameException.php 
<?php
namespace App\Exceptions;
use Exception;
class NoNameException extends Exception 
{
protected $message = "Missing user name";
}

and this is exactly what the helper function does, nothing special or magical about the function, its just a convenient way to wrap this in. The new helper functions are: throw_if and throw_unless

// 1. using throw_if exception helper function
User.php // user model
/**
* Get user name
* @return string
* @throws App\Exceptions\NoNameException
 **/
public function name()
{
throw_unless($this->name === null, throw new NoNameException);
// or throw_unless($this->name === null, NoNameException::class);
   return $this->name;
}

// 2. using throw_unless exception helper function which rids the 
// null comparison and throws exception unless the user has a name
User.php // user model
/**
* Get user name
* @return string
* @throws App\Exceptions\NoNameException
 **/
public function name()
{
throw_unless($this->name, throw new NoNameException);
// or throw_unless($this->name, NoNameException::class);
   return $this->name;
}

In both cases you get the same error like this

Exception Error displayed

These are pretty much what we did before, but have been wrapped into two helpful helper functions that will potentially clean up any code we write. It is entirely up to you if you decide to use them.

Thanks for reading

Stayed tuned for more on new in laravel 5.5

Show your support

Clapping shows how much you appreciated Mustapha’s story.