I’m trying to edit the data saved in my DB, and I’m completely lost.
In my PostController the index, create, store and show works nice, but in the edit and update I’m failing so much.
Error text
Undefined variable: id (View: C:laragonwwwlarablogresourcesviewsdashboardpostedit.blade.php)
PostController.php (appHttpControllersdashboardPostController.php)
public function edit($id) { $post = Post::findOrFail($id); return view ('dashboard.post.edit', ["post" => $post]); } public function update(Request $request, $id) { $post = Post::findOrFail($id); $post::update($request->validated()); return back() -> with('status', '¡Post editado con éxito!'); }
edit.blade.php (resourcesviewsdashboardpostedit.blade.php)
@extends('dashboard.master') @section('content') @include('dashboard.partials.validation-error') <form action="{{ route("post.update", $post->$id) }}" method="PUT"> @csrf <div class="form-group"> <label for="title">Título</label> <input class="form-control" type="text" name="title" id="title" value="{{ old('title', $post->title) }}"> @error('title') <small class="text-danger"> {{ $message }} </small> @enderror </div> <div class="form-group"> <label for="url_clean">Url limpia</label> <input class="form-control" type="text" name="url_clean" id="url_clean" value="{{ old('content', $post->url_clean) }}"> </div> <div class="form-group"> <label for="content">Contenido</label> <textarea class="form-control" type="text" name="content" id="content" rows="3"> {{ old('content', $post->content) }} </textarea> </div> <input type="submit" class="btn btn-primary" value="Enviar"> </form> @endsection
I don’t know why this error, I need a little theory to understand this.
Thanks you all!
P.D. I know if, in the PostController, I put:
public function edit(Post $post)
public function update($Request $request, Post $post)
I can’t avoid to write the:
$post = Post::findOrFail($id);
But I want to write like this in my first steps in laravel and futures id’s not called “id”
Advertisement
Answer
As the comment pointed out when you are passing parameters from $post you must do something like this
<form action="{{ route("post.update", $post->id) }}" method="POST"> @csrf @method(“PUT”)
Since you don’t have id variable. Besides this I highly HIGHLY recommend using route model binding, where you pass the whole model and not the id since it’s a lot cleaner and you don’t have to call findOrFail in every method. And also when updating use
$post->update($request->validated());
Since that is the correct way to call the update method, use ::update when you have Post model and not a variable.