Updating a record

Posted 10 months ago by behnampmdg3

Let's say we wanna update a record and make sure the column 'name' is unique.

This validation advised on Larvel website won't work because it finds the same record and the name is already taken obviously.

Which doesn't really make sense because the name is the name of the current book being updated of course it's taken.

public function update(Request $request, books $books)
    {
        $request->validate([
            'name' => 'bail|required|unique:books|max:255'
        ]);
        $book = \App\Books::find($request->id);
        $book->name = $request->name;
        $book->save();
        //
    }

I am thinking something like this. Which does the job but then I have to deal with redirects etc.

public function update(Request $request, books $books)
    {
        $books = \App\Books::where('id', '!=' , $request->id)
               ->where('name', $request->name)
               ->get()->count();
        if($books==0)
            {
                $request->validate([
                'name' => 'bail|required|max:255'
                ]);
                //$books = new Books;
                $book = \App\Books::find($request->id);
                $book->name = $request->name;
                $book->save();
                //
            }    
    }

Advice?

Please sign in or create an account to participate in this conversation.

Laracasts Mascot

Hi, Have We Met Yet?

Did you know that, in addition to the forum, Laracasts includes well over 1000 lessons on modern web development? All for the price of one lunch out per month.

Sign Me Up

Channels

Reply to

Use Markdown with GitHub-flavored code blocks.