Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

anderking's avatar

I want to send an abort when a user modifies the url with a nonexistent category

I have a category filterer.

public function scopeSearchCategory($query,$name)
{
    return $query->where('name', '=', $name);
}

And I need to send an abort (404) if a malicious user modifies the url with another category that does not exist for example:

from:

App / member / category / existing_name

to:

App / member / category / name_no_exist

I would prevent it with findOrFail when it was an id but as I am using a scope in the model Category

Here is the function in my controller:

public function searchcategories($name){
    $categories = Category::SearchCategory($name)->first();
    $articles = $categories->articles()->distinct()->groupBy('articles.id')->paginate(5);
    $articles->each(function($articles){
        $articles->category;
        $articles->images;
        $articles->tags;
    });
    return view('member.searchcategories')->with(['category_search'=>$categories,'article'=>$articles]);
}

So this shows me this error when a malicious user modifies the url:

FatalErrorException in MembersController.php line 116: Call to a member function articles() on null

How can i solve this?

0 likes
2 replies
Chris1904's avatar
Level 15
$categories = Category::SearchCategory($name)->firstOrFail();

you can easily do that or get() the collection and the check if it is empty. In case it is, throw an abort(404) or whatever other error code you want to output.

2 likes
AhimbisibweRoland's avatar

How about trying the firstOrFail such that an exception is thrown when there is no match

$categories = Category::SearchCategory($name)->firstOrFail();

then add something like this to your filters or any where you prefer

use IlluminateDatabaseEloquentModelNotFoundException;

App::error(function(ModelNotFoundException $e)
{
    return Response::make('Not Found', 404);
});

Please or to participate in this conversation.