Skip to content
Advertisement

Laravel: method parameter bypass

In my laravel (7.x) application, I have a method called _index in different controllers & models with exactly same functionality (fetch the data to display in the grid) and parameters (except 1, that requires an additional parameter called available).

So, I created a super method in the base controller, something line this:

Controller.php

namespace AppHttpControllers;

use IlluminateRoutingController as BaseController;

class Controller extends BaseController
{
    protected function _index($ModelClass, $status, $available = null)
    {
        # models
        $Model = new $ModelClass();

        # accessing and returning method data
        return $Model->_index(status: $status, available: $available);
    }
}

SomeController.php

class SomeController extends Controller
{
    public function _index()
    {
        # accessing super methods
        $SomeModel = $this->_index(SomeModel::class, true);

        ...

        # rendering
        return view('some-view', compact($SomeModel));
    }
}

class SomeModel extends Model
{
    public function _index($status = null, $available = null) : array
    {
        if($available == true)
        {
            ...
        }
    }
}

AnotherController.php

class AnotherController extends Controller
{
    public function _index()
    {
        # accessing super methods
        $AnotherModel = $this->_index(AnotherModel::class);

        ...

        # rendering
        return view('another-view', compact($AnotherModel));
    }
}

class AnotherModel extends Model
{
    public function _index($status = null) : array
    {
        ...
    }
}

Only SomeController / index is working fine but other controllers which does not required the $available parameter are showing Unknown named parameter $available.

Is there a way to ignore the missing parameters, as there is no point in including the parameter in the rest of the methods, throughout the application..?

Advertisement

Answer

I am not sure if this is the right way to handle this or not.

Controller.php

namespace AppHttpControllers;

use IlluminateRoutingController as BaseController;

class Controller extends BaseController
{
    protected function _index($ModelClass, $status, $available = null)
    {
        # models
        $Model = new $ModelClass();

        try
        {
            # accessing and returning method data
            return $Model->_index(status: $status, available: $available);
        }
        catch (Throwable $th)
        {
            # handling missing parameter error/exception
            if($th->getMessage() == 'Unknown named parameter $available')
            {
                return $Model->_index(status: $status);
            }
        }
    }
}

However, in case anybody finds a better way to handle this issue. Then do post your answer.

Thanks…

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement