Update not working in Resource Controller for Laravel 8

Previously, I was trying for a few hours to get my "destroy()" function working. Which would sound ridiculous to most of you but simply putting "method("DELETE")" in the form made it work, which I still don’t why.

Now, I’m stuck with the update() function. Once I click update, the page just reloads and does nothing. It doesn’t update the info in the database nor does it redirect me back to the index. Here’s the code:

Route (web.php):

Route::resource('books', BookController::class);

Form (Edit.blade.php):

    <div class="row">
        <div class="col-lg-12">
            <form action="{{ route('books.update', $book->id) }}" method="POST">
            <div class="mb-3 mt-3">
                <label for="exampleFormControlInput1" class="form-label">Book Title</label>
                <input type="text" name="title" class="form-control" value="{{ $book->title }}">
              <div class="mb-3">
                <label for="exampleFormControlTextarea1" class="form-label">Book Author</label>
                <input type="text" name="author" class="form-control" value="{{ $book->author }}" placeholder="Author Name..">
              <div class="btn-group" role="group">
                <button type="submit" class="btn btn-block btn-danger">Update</button>
                <a href="{{ route('books.index') }}"><button type="button" class="btn btn-success">Go Back</button></a>

Controller (BookController):

public function update(Request $request, Book $book)
    $validated = $request->validate([
        'title' => 'required|max:255|unique:books',
        'author' => 'required|max:255'

    return redirect()->route('books.index')->with('message','Book Updated!');

What am I doing wrong here? Some help would be appreciated.

>Solution :

I think the problem is in your unique validation. When you don’t change the title in the form and hit updated, the unique validation fails. It fails because title already exists in the database. We have to skip unique validation for the resource that is being updated.

$validated = $request->validate([
    'title' => 'required|max:255|unique:books,title,'.$book->id,  // <-- change this
    'author' => 'required|max:255'

Leave a Reply