pc_fuel
pc_fuel

Reputation: 786

Show a custom 404 blade for BadMethodCallException in Laravel 6

I am using dynamic controller actions for Laravel web routing. As an example,

if the controller is and a function inside it are :-

//namespaces and other traits and classes

class CountryController extends Controller{
   public function showAllCountry(){
     return view('all-countries');
   }
}

The url would be localhost/<projectfolder-name>/Country/showAllCountry

If the function or the controller does not exist, example if I type the URL as localhost/<projectfolder-name>/CountryCode/showAllCountry or localhost/<projectfolder-name>/Country/showMyCountry, etc. , it throws a BadMethodCallException as follows

BadMethodCallException
Method App\Http\Controllers\Country::showMyCountrydoes not exist.

or

BadMethodCallException
Method App\Http\Controllers\CountryCode::showAllCountry not exist.

What I want is, instead of doing that, it should show a custom 404 blade that I designed. How do I do it.

For reference, I am writing the Dynamic controller action from web.php here

web.php

Route::match(['get', 'post'], '{controller}/{action?}/{params1?}/{params2?}', function ($controller, $action = 'index', $params1 = '',$params2 = '') {

    $params = explode('/', $params1);
    $params[1] = $params2;
    $app = app();
    $controller = $app->make("\App\Http\Controllers\\" . ucwords($controller) . 'Controller');
    return $controller->callAction($action, $params);
})->middleware('supadminauth');

Upvotes: 0

Views: 128

Answers (1)

JawadR1
JawadR1

Reputation: 399

You can use PHP's method_exists() function to check if a function exists in class.

For example: In your route closure

if(! method_exists($controller, $action)) {
    return 404;
}
return $controller->callAction($action, $params);

Upvotes: 1

Related Questions