如何在表单请求上创建唯一验证(UPDATE / PATCH)的条件

时间:2017-12-31 21:33:48

标签: laravel validation laravel-5.2 unique

我试图通过将“验证请求”移动到名为“BookRequest”的表单请求来使控制器更清洁。

问题在于更新过程,我尝试创建一个条件来检查,如果它是PATCH或POST与以下代码

MyRequest.php

public function rules()
    {

        // Check Create or Update
        if ($this->method() == 'PATCH') 
        {
            $a_rules = 'required|string|size:6|unique:books,column2,' .$this->get('id');
            $b_rules = 'sometimes|string|size:10|unique:books,column3,' .$this->get('id');
        }

        else 
        {
            $a_rules = 'required|string|size:6|unique:books,column2';
            $b_rules = 'sometimes|string|size:10|unique:books,column3';
        }

        return [
            'column1'             => 'required|string|max:100',
            'column2'             => $a_rules,
            'column3'              => $b_rules,
            'column4'    => 'required|date',
            'column5'            => 'required|in:foo,bar',
            'column6'        => 'required',
            'column7'       => 'required',
            'column8'       => 'required',
        ];

    }

.$this->get('id')它失败了,表单仍然在更新时处理唯一。

控制器@更新

public function update($id, BookRequest $request)
{
    $book = Book::findOrFail($id);
    $input = $request->all();
    $book->update($request->all());
    return view('dashboards.book');
}

控制器@修改

public function edit($id)
{

    $book = Book::findOrFail($id);


    return view('dashboards.edit', compact('book'));
}

控制器@创建

public function create()
{

    return view('dashboards.create');
}

控制器@存储

public function store(BookRequest $request)
{


    $input = $request->all();
    $book = Book::create($input);

    return redirect('dashboards/book/index');
}

我尝试了替代.$book->id,它给我一个 ErrorException 未定义的变量:book

有什么建议吗?我顺便使用Laravel 5.2

1 个答案:

答案 0 :(得分:1)

您使用预订作为路线参数,但尝试使用 ID 。试试这个 -

if ($this->method() == 'PATCH') 
    {
        $a_rules = 'required|string|size:6|unique:books,column2,' .$this->route()->parameter('book');
        $b_rules = 'sometimes|string|size:10|unique:books,column3,' .$this->route()->parameter('book');
    }

希望有所帮助:)