Answer the question
In order to leave comments, you need to log in
How to display an error about a non-existent entry in the database?
рут Route::get('/post/{id}', '[email protected]');
Model
<?php namespace App\models;
use Illuminate\Database\Eloquent\Model;
use PhpSpec\Exception\Exception;
class Post extends Model
{
public static function get($id)
{
try {
$post = Post::where('id', '=', $id)->firstOrFail();
} catch (Exception $e) {
return $e;
}
return $post;
}
}
Controller
<?php namespace App\Http\Controllers;
use App\Models\Post;
use Psy\Exception\Exception;
class PostController extends Controller
{
public function getPost(Exception $id)
{
$id = (int)$id;
$post = Post::get($id);
if ($post instanceof CustomException) {
return "error";
}
return view('post.showPost', ['post'=>$post]);
}
}
Answer the question
In order to leave comments, you need to log in
Why do you need to catch
use PhpSpec\Exception\Exception
} catch (Exception $e) {
при промохе бросается
Illuminate\Database\Eloquent\ModelNotFoundException
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question