Update Post Laravel Vue

User
update post in laravel vue js interia js
Assistant
To update a post in a Laravel application with Vue.js and Inertia.js, follow these steps:

### Backend (Laravel)
1. **Define a Route**:
Add a route in your `web.php` file to handle the update request.

use AppHttpControllersPostController;

   Route::put('/posts/{id}', [PostController::class, 'update'])->name('posts.update');

2. **Update Method in Controller**:
Create an `update` method in your `PostController`.

namespace AppHttpControllers;

   use IlluminateHttpRequest;
   use AppModelsPost;

   class PostController extends Controller
   {
       public function update(Request $request, $id)
       {
           $validated = $request->validate([
               'title' => 'required|string|max:255',
               'content' => 'required|string',
           ]);

           $post = Post::findOrFail($id);
           $post->update($validated);

           return redirect()->route('posts.index')->with('success', 'Post updated successfully.');
       }
   }

3. **Ensure the Model is Fillable**:
Add `title` and `content` to the `$fillable` property in the `Post` model.

namespace AppModels;

   use IlluminateDatabaseEloquentFactoriesHasFactory;
   use IlluminateDatabaseEloquentModel;

   class Post extends Model
   {
       use HasFactory;

       protected $fillable = ['title', 'content'];
   }

### Frontend (Vue.js + Inertia.js)

1. **Create an Edit Form**:
In your Vue.js component, create a form for editing the post.

<template>
       <div>
           <h1>Edit Post</h1>
           <form @submit.prevent="updatePost">
               <div>
                   <label for="title">Title</label>
                   <input
                       type="text"
                       id="title"
                       v-model="form.title"
                       :class="{ 'border-red-500': errors.title }"
                   />
                   <div v-if="errors.title" class="text-red-500">{{ errors.title }}</div>
               </div>

               <div>
                   <label for="content">Content</label>
                   <textarea
                       id="content"
                       v-model="form.content"
                       :class="{ 'border-red-500': errors.content }"
                   ></textarea>
                   <div v-if="errors.content" class="text-red-500">{{ errors.content }}</div>
               </div>

               <button type="submit">Update Post</button>
           </form>
       </div>
   </template>

   <script>
   import { ref } from 'vue';
   import { useForm } from '@inertiajs/vue3';

   export default {
       props: {
           post: Object,
       },
       setup(props) {
           const form = useForm({
               title: props.post.title,
               content: props.post.content,
           });

           const updatePost = () => {
               form.put(route('posts.update', props.post.id), {
                   onSuccess: () => {
                       alert('Post updated successfully!');
                   },
               });
           };

           return { form, updatePost, errors: form.errors };
       },
   };
   </script>

2. **Pass Data from the Backend**:
In your controller's edit method (or equivalent), pass the post data to the view.

public function edit($id)
   {
       $post = Post::findOrFail($id);
       return inertia('Posts/Edit', ['post' => $post]);
   }

3. **Add the Route to the Edit Page**:
Define a route for the edit page.

Route::get('/posts/{id}/edit', [PostController::class, 'edit'])->name('posts.edit');

### Key Points
– Use `useForm` from Inertia to handle form state and validation errors.
– Define the `update` route with the `PUT` HTTP method.
– Redirect after a successful update to a relevant page (e.g., posts index or post details).
– Ensure your `Post` model is fillable to avoid mass assignment issues.

Leave a Comment

Your email address will not be published. Required fields are marked *