Form to edit records in Laravel Inertia with Vue

- Andrés Cruz

En español
Form to edit records in Laravel Inertia with Vue

Forms are a common tool used to collect information from users. In the update process, a form can be used to update information that is stored in the database; the update process often begins when a user selects the record they want to update from a list of records and with this, goes to the editing form that already has the identifier of the record that the user wants to modify, this identifier is generally set to URL; Like any form, it can have any type of field supported in HTML present.

Once the user has edited the form information, they can submit the form by clicking an "Update" or "Submit" button so that Laravel takes care of the validations and subsequent saving in the database if the data is correct or display validation errors.

Editing forms in Inertia

We already know how to handle a basic form in Inertia to create records; but what if what you need is editing; for that, we can use practically the same scheme as the one presented above, but with some modifications.

From the edit controller in Laravel, we pass the reference to the registry:

    public function edit(Category $category)
    {
        return inertia("Dashboard/Category/Edit", compact('category'));
    }

So, we already have a record to receive from the component in Vue:

  props: {
    errors: Object,
    category: Object,
  },

And with the reference to the category, we update the form through the v-model:

  setup(props) {
    const form = useForm({
      id: props.category.id,
      title: props.category.title,
      slug: props.category.slug,
    });

And now, we change the route of the form from type post to put or patch:

    function submit() {
      Inertia.put(route("category.update",form.id), form);
    }

Finally, it looks like:

<template>
    <app-layout >
      <jet-form-section @submitted="submit" class="max-w-7xl mx-auto py-10 sm:px-6 lg:px-8">
        <template #title> Create Category </template>
        <template #description> Create a Category </template>
        <template #form>
          <div class="col-span-6">
            <jet-label>Title</jet-label>
            <jet-input class="w-full" type="text" v-model="form.title" />
            <jet-input-error :message="errors.title" />
          </div>
          <div class="col-span-6">
            <jet-label value="Slug" />
            <jet-input class="w-full" type="text" v-model="form.slug" />
            <jet-input-error :message="errors.slug" />
          </div>
        </template>
        <template #actions>
          <jet-button type="submit">Send</jet-button>
        </template>
      </jet-form-section>
    </app-layout>
</template>
 
<script>
import { Inertia } from "@inertiajs/inertia";
import { useForm } from "@inertiajs/inertia-vue3";
// import AppLayout from "../../../Layouts/AppLayout"
import AppLayout from "@/Layouts/AppLayout";
import JetInput from "@/Jetstream/Input";
import JetInputError from "@/Jetstream/InputError";
import JetLabel from "@/Jetstream/Label";
import JetButton from "@/Jetstream/Button";
import JetFormSection from "@/Jetstream/FormSection";
export default {
  components: {
    AppLayout,
    JetInput,
    JetInputError,
    JetLabel,
    JetButton,
    JetFormSection,
  },
  props: {
    errors: Object,
    category: Object,
  },
  setup(props) {
    const form = useForm({
      id: props.category.id,
      title: props.category.title,
      slug: props.category.slug,
    });
    function submit() {
      Inertia.put(route("category.update",form.id), form);
    }
    return { form, submit };
  },
};
</script>
Y en el controlador para actualizar:
    public function update(Put $request, Category $category)
    {
        $category->update($request->validated());
    }
Con su validador:
<?php
namespace App\Http\Requests\Category;
use Illuminate\Foundation\Http\FormRequest;
class Put extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }
    public function prepareForValidation()
    {
        if(str($this->slug)->trim() == "")
        $this->merge([
            'slug' => str($this->title)->slug()
        ]);
    }
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, mixed>
     */
    public function rules()
    {
        return [
            "title" => "required|min:5|max:255",
            "slug" => "required|min:5|max:255|unique:categories,slug,".$this->route("category")->id
        ];
    }
}
Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.