I
I
ImPuuLsE2015-08-26 17:02:16
Laravel
ImPuuLsE, 2015-08-26 17:02:16

How to validate a unique field in Larvel 5?

Hello! there is the following record update code

public function update(Request $request, $id)
    {
        $page = Page::findOrFail($id);
        $this->validate($request, [
            'title' => 'required',
            'description' => 'required',
            'slug' => 'required|unique:pages',
            'status' => 'required',
            'type' => 'required',
        ]);
        $input = $request->all();
        $page->fill($input)->save();
        \Session::flash('page_updated', 'Страница обновлена!');

        return redirect()->route('adminPages');
    }

It turns out that when a record is created, a slug is formed, and when the same record is updated, it says that such a slug is already used, although it is the same and there are no identical ones in the database. How to be?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
D', 2015-08-26
@ImPuuLsE

We read here laravel.com/docs/5.1/validation#rule-unique
Specifically, the section " Forcing A Unique Rule To Ignore A Given ID "
That is, in this case it will be like this:

'slug' => 'required|unique:pages,slug,' . $page->id,

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question