Search code examples
phprequestlaravel-5.3

Laravel 5.3 throws error formrequest


I've made a request class in Laravel 5.3. Looks like this:

<?php

namespace App\Http\Requests\User;

use Illuminate\Foundation\Http\FormRequest;

class StoreRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name'              => 'required|max:25|min:2'
        ];
    }
}

But when I use that in my controller I receive:

NotFoundHttpException in RouteCollection.php line 161:

When I remove the rules so it looks like this:

public function rules()
{
   return [

   ];
}

It suddenly works !?!?

--UPDATE--

It looks like the validator looks in my web.php but I don't have a route there (that's why I receive the exception: NotFoundHttpException in RouteCollection.php line 161:). I didn't have this problem in 5.2. What should I do?

--UPDATE--

My current routes:

| Domain | Method    | URI                                           | Name         | Action                                            | Middleware |
+--------+-----------+-----------------------------------------------+--------------+---------------------------------------------------+------------+
|        | POST      | api/login                                     |              | App\Http\Controllers\Auth\AuthController@login    | api        |
|        | GET|HEAD  | api/register/{user}/verify/{ConformationCode} |              | App\Http\Controllers\Auth\AdminController@confirm | api        |
|        | GET|HEAD  | api/user                                      | user.index   | App\Http\Controllers\User\UserController@index    | api,active |
|        | POST      | api/user                                      | user.store   | App\Http\Controllers\User\UserController@store    | api,active |
|        | GET|HEAD  | api/user/create                               | user.create  | App\Http\Controllers\User\UserController@create   | api,active |
|        | GET|HEAD  | api/user/{user}                               | user.show    | App\Http\Controllers\User\UserController@show     | api,active |
|        | PUT|PATCH | api/user/{user}                               | user.update  | App\Http\Controllers\User\UserController@update   | api,active |
|        | DELETE    | api/user/{user}                               | user.destroy | App\Http\Controllers\User\UserController@destroy  | api,active |
|        | GET|HEAD  | api/user/{user}/edit                          | user.edit    | App\Http\Controllers\User\UserController@edit     | api,active 

Also if try this with a fresh Laravel 5.3 install I receive the error!

Perhaps it has something to do with:

in Laravel 5.3 UserStoreRequest

extends FormRequest (use Illuminate\Foundation\Http\FormRequest;)

And in Laravel 5.2 UserStoreRequest

extends Request (use App\Http\Requests\Request;)

--EDIT--

API.PHP

<?php

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/


Route::post('/login', 'Auth\AuthController@login');
Route::get('/register/{user}/verify/{ConformationCode}', 'Auth\AdminController@confirm');
Route::put('/test', 'User\UserController@test');

Route::group(['middleware' => ['active']], function () {
    Route::resource('user',         'User\UserController');
    Route::resource('corporation',  'Corporation\CorporationController');
    Route::resource('forum',        'Forum\ForumController');
    Route::resource('topic',        'Topic\TopicController');
});

Store method

 public function store(StoreRequest $request)
    {
        if($this->authorize($this->user))
        {
            $user = $this->userInfo->store($request);
            event(new UserRegistered($user));

            return response()->json(['success' => 'gebruiker succesvol aangemaakt. Welkom email verzonden.']);
        }

        return response()->json(['error' => 'niet geautoriseerd'], 401);
    }

Solution

  • This happens because the FormRequest::response function wants to redirect you to a page with the errors. But because you don't have any web routes (only api routes), it will fail with a NotFoundHttpException. If you had any web routes, it would have (internally) redirected you to the root.

    If you look inside of that FormRequest::response function, you can see this bit:

    if($this->expectsJson()) {
        return new JsonResponse($errors, 422);
    }
    

    So if you can fullfill the expections in expectsJson, it works as expected.

    You can do this in a couple of ways:

    • Make sure the request is an XMLHttpRequest by supplying the X-Requested-Withheader.
    • Supply a X-PJAX header
    • Supply a Accept header with application/json
    • Overwrite the wantsJson call on the request to always return true. Like so:

    class JsonRequest extends Request { public function wantsJson() { return true; } }