Home > Back-end >  Update not working in Resource Controller for Laravel 8
Update not working in Resource Controller for Laravel 8

Time:05-19

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):

@section('content')
    <div >
        <div >
            <form action="{{ route('books.update', $book->id) }}" method="POST">
                @csrf
                @method('PUT')
            <div >
                <label for="exampleFormControlInput1" >Book Title</label>
                <input type="text" name="title"  value="{{ $book->title }}">
              </div>
              <div >
                <label for="exampleFormControlTextarea1" >Book Author</label>
                <input type="text" name="author"  value="{{ $book->author }}" placeholder="Author Name..">
              </div>
              <div  role="group">
                <button type="submit" >Update</button>
                <a href="{{ route('books.index') }}"><button type="button" >Go Back</button></a>
              </div>
            </form>
        </div>
    </div>
@endsection

Controller (BookController):

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

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

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

CodePudding user response:

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'
]);

CodePudding user response:

In your Book model, have you set the db fields either fillable or guarded? Also, are you getting any errors? Under your validated block try dd($request->all()) to see what you're getting from the request. It looks like everything should work but hard to tell without any errors.

  • Related