AlexanderKim
AlexanderKim

Reputation: 1

How to show error is not an existing record?

model Post.php

<?php namespace App\models;

use Illuminate\Database\Eloquent\Model;
use PhpSpec\Exception\Exception;

class Post extends Model
{

    public static function get(Exception $id)
    {
        try {
            $post = Post::where('id', '=', $id)->firstOrFail();
        } catch (isHttpException $e) {
            return abort(404, 'Post Not Found');
        }
        return $post;
    }
}

controller PostController.php

<?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);
        return view('post.showPost', ['post'=>$post]);
    }
}

Error I get:

BindingResolutionException in Container.php line 785: 
Target [Psy\Exception\Exception] is not instantiable.

I dont understand the error/exception. What is wrong with my code?

Upvotes: 0

Views: 322

Answers (1)

Kyslik
Kyslik

Reputation: 8385

Your problem is simple you are "casting" parameter as exception which is wrong;

model

public static function get($id) {...}

controller

public function getPost($id) {...}

sidenote

you do NOT need this line in your code:

$id = (int)$id;

Full example (should work, not tested)

model Post.php

<?php namespace App\models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $table = 'posts'; //assuming posts table exists...

    public static function getById($id)
    {
        return Post::findOrFail($id);
    }
}

controller PostController.php

<?php namespace App\Http\Controllers;
use App\Models\Post;

class PostController extends Controller
{

    public function getPost($id)
    {
        $post = Post::getById($id);
        return view('post.showPost')->withPost($post);
    }
}

For ModelNotFoundException follow this answer or

With commit from today (9db97c3), all you need to do is add a 404.blade.php file in the /resources/views/errors/ folder and it will find and display it automatically.

Upvotes: 1

Related Questions