Ceci est une ancienne révision du document !
Pour éviter les multiples codes du style
public function show($id){
$mymodel = MyModel::find($id);
if(is_null($mymodel))
return to_route('dashboard')->with('flash_error', "Erreur : le model n'existe pas.");
On peut factoriser le truc avec une exception
php artisan make:exception MyModelNotFoundException
<?php
namespace App\Exceptions;
use Exception;
class MyModelNotFoundException extends Exception
{
// public function __construct($message = null, $code = 0)
// {
// if (!$message) {
// throw new $this('Unknown '. get_class($this));
// }
// parent::__construct($message, $code);
// }
public function render($request)
{
return to_route('dashboard')->with('flash_error',$this->getMessage());
}
}
Dans le model on rajoute une methode static
public static function getFind($id){
$mymodel = MyModel::find($id);
if(is_null($mymodel))
throw new MyModelNotFoundException("Erreur : le model n'existe pas.");
Et le code devient maintenant plus simple
public function show($id){
$mymodel = MyModel::getFind($id);