在自定义表单请求中找不到路由

时间:2016-10-08 09:12:10

标签: php laravel laravel-5.2 laravel-routing

我使用带有命令php artisan make:request AddressBookRequest的laravel自定义表单请求 并在我的控制器中使用该请求,如:

public function add_address_book($lang,$user_id,AddressBookRequest $request){
 dd($request);
}

当我运行api route laravel时:

 NotFoundHttpException in RouteCollection.php line 161:

但当我将AddressBookRequest更改为Request时:

 public function add_address_book($lang,$user_id,Request $request){
 dd($request);
}

Api工作正常

AddressBookRequest:

<?php namespace App\Http\Requests;

 use App\Http\Requests\Request;

class AddressBookRequest extends Request
{
/**
 * 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 [
              'title' => 'required',
              'address' => 'required',
              'latitude' => 'required',
              'longitude' => 'required'
          ];
}

public function messages()
{
    return [
              'title.required' => trans('address_book.title_required'),
              'address.required' => trans('address_book.address_required'),
              'latitude.required' => trans('address_book.latitude_required'),
              'longitude.required' => trans('address_book.longitude_required'),
    ];
}


}

AddressBookController用例:

<?php namespace App\Http\Aggregate\Address_book\Controller\v1_0;

 use App\Http\Requests\AddressBookRequest;
 use Illuminate\Routing\Controller as BaseController;
 use EventHomes\Api\ApiController;
 use JWTAuth;

 class AddressBookController extends BaseController
 {

路线:

  Route::group(['namespace' => 'Aggregate\Address_book\Controller\v1_0', 'middleware' => 'jwt.auth', 'prefix' => 'api/v1.0/{lang}'], function () {
   Route::post('customer/{id}/address_book', 'AddressBookController@add_address_book');
  });

如何修复它以使用自定义请求?

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:1)

您应该将此行添加到控制器的顶部:

use App\Http\Requests\AddressBookRequest;

另外,请确保自定义请求类中的authorize()方法返回true

public function authorize()
{
    return true;
}

答案 1 :(得分:0)

我通过添加:

来修复它
 use Illuminate\Foundation\Http\FormRequest;
 use EventHomes\Api\ApiController;

 abstract class Request extends FormRequest
 {
    use ApiController;

    public function response(array $errors)
    {
       foreach($errors as $key=>$error)
       {
         return $this->respondUnprocessable(1004,'validation',$errors[$key][0]);
       }
    }

}

requst.php