Admin Category Management

User
store cateogries in admin area and save to db
Assistant
To store categories in the admin area and save them to the database in your Laravel application, follow these steps:

### **1. Create the Categories Migration**
Run the following command to generate a migration file:

php artisan make:migration create_categories_table --create=categories

Edit the migration file (`database/migrations/YYYY_MM_DD_create_categories_table.php`):

use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;

return new class extends Migration {
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('slug')->unique();
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('categories');
    }
};

Run the migration:

php artisan migrate

### **2. Create the Category Model**
Run:

php artisan make:model Category

Edit the `app/Models/Category.php`:

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
use IlluminateSupportStr;

class Category extends Model
{
    use HasFactory;

    protected $fillable = ['name', 'slug'];

    public static function boot()
    {
        parent::boot();

        static::creating(function ($category) {
            $category->slug = Str::slug($category->name);
        });
    }
}

### **3. Create CategoryController**
Run:

php artisan make:controller Admin/CategoryController --resource

Modify `app/Http/Controllers/Admin/CategoryController.php`:

namespace AppHttpControllersAdmin;

use AppHttpControllersController;
use AppModelsCategory;
use IlluminateHttpRequest;

class CategoryController extends Controller
{
    public function index()
    {
        $categories = Category::latest()->paginate(10);
        return inertia('Admin/Categories/Index', compact('categories'));
    }

    public function create()
    {
        return inertia('Admin/Categories/Create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|unique:categories|max:255',
        ]);

        Category::create([
            'name' => $request->name,
        ]);

        return redirect()->route('admin.categories.index')->with('success', 'Category created successfully.');
    }

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

    public function update(Request $request, Category $category)
    {
        $request->validate([
            'name' => 'required|unique:categories,name,' . $category->id,
        ]);

        $category->update(['name' => $request->name]);

        return redirect()->route('admin.categories.index')->with('success', 'Category updated successfully.');
    }

    public function destroy(Category $category)
    {
        $category->delete();
        return redirect()->route('admin.categories.index')->with('success', 'Category deleted successfully.');
    }
}

### **4. Define Routes**
In `routes/web.php`:

use AppHttpControllersAdminCategoryController;

Route::middleware(['auth', 'admin'])->prefix('admin')->name('admin.')->group(function () {
    Route::resource('categories', CategoryController::class);
});

### **5. Create Vue Components for Admin**
#### **`resources/js/Pages/Admin/Categories/Index.vue`**

<template>
  <div>
    <h1 class="text-2xl font-bold mb-4">Categories</h1>
    <Link :href="route('admin.categories.create')" class="btn-primary">Add Category</Link>
    <table class="table-auto w-full mt-4">
      <thead>
        <tr>
          <th class="border px-4 py-2">ID</th>
          <th class="border px-4 py-2">Name</th>
          <th class="border px-4 py-2">Actions</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="category in categories.data" :key="category.id">
          <td class="border px-4 py-2">{{ category.id }}</td>
          <td class="border px-4 py-2">{{ category.name }}</td>
          <td class="border px-4 py-2">
            <Link :href="route('admin.categories.edit', category.id)" class="text-blue-500">Edit</Link> |
            <button @click="deleteCategory(category.id)" class="text-red-500">Delete</button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script setup>
import { defineProps } from "vue";
import { Link, router } from '@inertiajs/vue3';

defineProps({
  categories: Object,
});

const deleteCategory = (id) => {
  if (confirm("Are you sure you want to delete this category?")) {
    router.delete(route("admin.categories.destroy", id));
  }
};
</script>

#### **`resources/js/Pages/Admin/Categories/Create.vue`**

<template>
  <div>
    <h1 class="text-2xl font-bold mb-4">Create Category</h1>
    <form @submit.prevent="submit">
      <div class="mb-4">
        <label class="block">Name</label>
        <input v-model="form.name" type="text" class="border p-2 w-full">
      </div>
      <button type="submit" class="btn-primary">Save</button>
    </form>
  </div>
</template>

<script setup>
import { reactive } from "vue";
import { useForm } from '@inertiajs/vue3';

const form = useForm({
  name: '',
});

const submit = () => {
  form.post(route("admin.categories.store"));
};
</script>

#### **`resources/js/Pages/Admin/Categories/Edit.vue`**

<template>
  <div>
    <h1 class="text-2xl font-bold mb-4">Edit Category</h1>
    <form @submit.prevent="submit">
      <div class="mb-4">
        <label class="block">Name</label>
        <input v-model="form.name" type="text" class="border p-2 w-full">
      </div>
      <button type="submit" class="btn-primary">Update</button>
    </form>
  </div>
</template>

<script setup>
import { reactive } from "vue";
import { useForm } from '@inertiajs/vue3';
import { defineProps } from "vue";

const props = defineProps({
  category: Object,
});

const form = useForm({
  name: props.category.name,
});

const submit = () => {
  form.put(route("admin.categories.update", props.category.id));
};
</script>

### **6. Add Styling and Tailwind Configuration**
Ensure you have Tailwind CSS installed and configured in `postcss.config.js`:

module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
};

Add the Tailwind directives in `resources/css/app.css`:

@tailwind base;
@tailwind components;
@tailwind utilities;

### **7. Build and Test**
Run the following:

yarn dev
php artisan serve

Now, you can manage categories in your admin area using Laravel with Vue.js and Inertia.js.

Would you like any further customizations, such as category nesting (subcategories) or bulk actions? ๐Ÿš€

Leave a Comment

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