learner1982
1 month ago

Refactor: Request in Controller & Calling other methods, any ideas?

Posted 1 month ago by learner1982

I often find myself in situation where I have a method in a controller like:

public function store(ProfileRequest $request){
    // ....
}

Good thing: I can validate the data before it hits the controller.

Sometimes I want to call the same store method, from another method in the same class. In reality, in this situation I would like to call the store method like:

store($name, $age, $city) 

and not with the Request object.

If just php had method overloading :D

How do you handle these two situations?

Possible solutions:

Solution A: create two methods

public function storeRequest(ProfileRequest $request){ 
    $this->store($request['name]', $request['age'], $request['city']);
}
public function store($name, $age, $city)

Solution B: I guess its possible to move the Request/Validation to the api.php/web.php and then in the call the method in the controller with its parameter... but I dont know how it should look??????

Route::put('/update', function (ProfileRequest $request) {
    \App\ProfileControlller::store($request ['name'], $request ['age'], $request ['city'])  ???????????????????????????
});

How do I do this?

What are other approaches, you can recommend?

Thanks :-)

Please sign in or create an account to participate in this conversation.