PHP code example of imanghafoori / laravel-nullable

1. Go to this page and download the library: Download imanghafoori/laravel-nullable library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

imanghafoori / laravel-nullable example snippets



$email = TwitterApi::find(1)->email;


$user = $twitterApi->find($id);

if ($user === null) {
    return redirect()->route('page_not_found');
}



// the old way:

/**
* @return User|null            <---- consider here. We are returning two types !!!
*/
public function find ($id) {
     $user = TwitterApi::search($id);
     
     if (!$user) {
         return null;
     }
     return new User($user);   
}

/**
 * @return Nullable        <---- we now have only one consistent type. Not two.
 */
public function find ($id) {
     $user = TwitterApi::search($id);
     
     if (!$user) {
         return new Nullable(null);   //  <----  instead of pure null;
     }
     $user = new User($user);   
     
     $message = 'Model Not Found with Id : '. $id;

     return new Nullable($user, [$message]);   //  <----  instead of User;
}


$userObj = $userRepo->find($id)->getOrSend(function ($message) {

  return redirect()->route('page_not_found')->with('error', $message);
});

// Call a static method.
$userObj = $twitterApi->find($id)->getOrSend([Response::class, 'pageNotFound']);

// or a get default value
$userObj = $twitterApi->find($id)->getOr(new User());