0

I want to devide my controller to several service layer, validation layer, and logical layer. But I got stuck when I want to send new variable to validation request, my schenario is, if there is a new sent it indicates for new data, and if new variable is not exists it indicates it's updating data.

Here is my Controller:

    public function store(AlbumRequest $request, AlbumService $service)
    {
        $request->add(['new' => true])
        try{
            $service->store($request);
            return redirect(route('admin.web.album.index'));
        }catch(\Exception $err){
            return back()->withInput()->with('error',$err->getMessage());
        }    
    }

Here is my Request

class AlbumRequest extends FormRequest
{
    public function rules()
    {
        dd($this->request->get('new')
    }
}

I want to catch variable I have sent from Controller to Request. How to do that? Thank you.

4 Answers4

1

You can add new parameter in request from controller like that

$request->merge(array('new' => true));
Raj Vadi
  • 106
  • 4
0

before your request reaches your controller , it has to go through AlbumRequest class . so you have to merge that field in AlbumRequest class by using method prepareForValidation :

protected function prepareForValidation()
{
    $this->merge([
        'new' => true,
    ]);
}

add this method in your AlbumRequest class and see if it works

0

I am afraid you cannot do that because the incoming form request is validated before the controller method is called. Now if you want to know whether the request is for creating something new or updating something, you can do it by accessing the route parameters and method type

public function rules()
{
    $rules = [
        'something' => 'required',
    ];

    if (in_array($this->method(), ['PUT', 'PATCH'])) {
        //it is an edit request
        //you can also access router parameter here, $this->route()->parameter('other thing');

        $rules['somethingelse'] = [
            'required',
        ];
    }

    return $rules;
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
-1

You can enter the requested class as URL params.

    class AlbumRequest extends FormRequest
{
    public function rules()
    {
        dd(request()->get('new')
    }
}