Call to undefined method firstOrFail

Question

Hi,

I’m getting this error with Laravel when I try to access a page on my blog.

Call to undefined method IlluminateDatabaseQueryBuilder::firstOrFail()

This is the query I changed:

$category = DB::table('blog_post_categories')->where('slug', $slug)->firstOrFail();

What am I doing wrong?

Answer ( 1 )

    0
    2023-01-25T17:44:32+00:00

    You cannot use the firstOrFail method with the query builder. You need to use it with Eloquent model.

    Try this

    $category = BlogCategory::where('slug', $slug)->firstOrFail();

    Change the model name if I didn’t get it right.

Leave an answer