T
T
The Dragger2015-06-09 16:09:45
Laravel
The Dragger, 2015-06-09 16:09:45

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]);
    }
}

I want to throw an error on a non-existent entry in the database by id, but instead of my error Error, the debugger works - Whoops, looks like something went wrong.
1/1
ModelNotFoundException in Builder.php line 151:
No query results for model [App\models\Post].

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vyacheslav Plisko, 2015-06-10
@AmdY

Why do you need to catch

use PhpSpec\Exception\Exception
 } catch (Exception $e) {
при промохе бросается 
Illuminate\Database\Eloquent\ModelNotFoundException

And the rest of the code is strange getPost(Exception $id) - why the controller accepts an exception as a parameter
public static function get($id) - no need to use statics, laravel will call the object method through the facade,
respectively, the line
$post = Post::where(' id', '=', $id)->firstOrFail();
becomes
return $this->findOrFail($id);
well, and further it is not clear why this method should be produced at all, why catch an exception in the controller, etc.
You should also try binding models to rotting ...
In general, I advise you to carefully reread the documentation

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question