maximl337's avatar

Laravel 5 Custom Request not working

Something weird is happening in my app:

Route:

Route::resource('users', 'UserController');

Controller:

use App\Http\Requests\UserRequest;
...

public function store(UserRequest $request) {

dd($request);

}

UserRequest:

public function authorize()
{
    return true;
}

public function rules()
{
    return [
        'email'         => 'required|email',
        'password'    => 'required'
    ];
}

When I make a POST to /users , it redirects to "/"

if I change the injection to:

public function store(Request $request)

It works as intended.

0 likes
10 replies
pmall's avatar

Do you post with email and password data ?

RachidLaasri's avatar

Then it is working if it redirected you back. try to dd() errors on your view.

maximl337's avatar

@RachidLaasri I dont have a view - I'm using Postman.

I understand - If the Request validation fails it will not enter the method.

How would I return a json response in that case ( when building an API ) ?

RachidLaasri's avatar

Laravel will automatically determine if you are posting an ajax request and return a json response for you.

pmall's avatar

@maximl337 you have to specify in your request headers you accept json as response.

This way the $request->wantJson() method will return true and the form request will return errors as json.

A form request will return errors as json if either $request->wantJson() or $request->isAjax() return true.

1 like
joedawson's avatar

Did you work this out @maximl337?

I specified my request headers @pmall, I'm not sending any form-data as I'm expecting some errors.

Screenshot

It still returns a RedirectResponse. Rather than some errors, which if you're correct is what it's supposed to return?

maximl337's avatar

@JoeDawson : Yes I figured it out. By default Laravels FormRequest will return a redirect, when using POSTMAN it will simply redirect you, if unit testing it will respond with a 302, if its an ajax request it will send the json respond.

if you want you can change this behavior in Illuminate\Foundation\Http\FormRequest in the response() method, you'll understand when you see it. Although its recommended not to overwrite core files.

pmall's avatar

@JoeDawson you have set the Content-Type header, you have to set the Accept header.

Accept: application/json

2 likes

Please or to participate in this conversation.