我可以在php artisan make:request的请求中获取Url参数(例如id)

时间:2019-11-25 10:16:13

标签: php laravel

我想创建一个由php artisan make:request发出的请求,其中可以添加规则的规则,例如,我在控制器中具有以下验证器:

      $validator = Validator::make($request->all(), [
            'title' => 'required|unique:posts|max:{{number}}',
            'body' => 'required',
        ]);

其中数字来自url参数 如何在我的Request类中获取此url参数?

这是我的请求类:

<?php

namespace Modules\Blog\Http\Requests;

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;

class SaveBlogCategoriesRequest extends FormRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        dd($request->param);
        return [
            'lang' => 'required',
            'name' => 'required',
            'slug' => "required|unique:blog_categories_id,slug,", // here I want to add id from param
        ];
    }

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

    protected function failedValidation(Validator $validator)
    {
        $data = [
                'status' => false,
                'validator' => true,
                'msg' => [
                    'e' => $validator->messages(),
                    'type' => 'error'
                ],
        ];

        throw new HttpResponseException(response()->json($data));
    }
}

2 个答案:

答案 0 :(得分:2)

对于请求类,您无需实例化验证器

class ModelCreateRequest extends FormRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        //if you need the input, you can access it via $this->request;
        $param = $this->request->get('param');
        //or you can also access it directly (yeah I know it not intuitive)
        $param = $this->param
        return [
            'lang' => 'required',
            'name' => 'required',
            'slug' => "required|unique:blog_categories_id,slug,".$param,
        ];
    }
}

答案 1 :(得分:0)

使用dd($this)获取请求类中的请求对象