ホーム > Laravel > How to Implement a Category Functionality in Laravel
Laravel

How to Implement a Category Functionality in Laravel

Thank you for your continued support.
This article contains advertisements that help fund our operations.

関連動画

Related Video

This is a video where we actually tried out the content from the article! If anything is unclear in the article, please check out the video.

The video provides further explanations and demonstrations, so it should be helpful.

Subscribe to Our Channel

If you found this video helpful, please consider subscribing to our channel or giving it a thumbs up! It really motivates us to create more content.

Questions and Feedback

If you have any questions or feedback regarding this article or the video, feel free to leave them in the comment section of the video. Your input is greatly appreciated and will help us improve our content in the future!

⇨ Laravel Article Index

This article summarizes how to implement category functionality in Laravel posts.

What We’ll Do

We’ll start from a simple feature that allows posting a title and content, and extend it to select a category when posting and display that category.

Steps

  1. Add a category_id column to the posts table.
  2. Create a categories table and prepare categories.
  3. Use the prepared categories to create a save page.
  4. Save the category_id during submission.
  5. Display categories using relationships.

If you’re not familiar with posting functionality, please refer to this article:

【Beginner-Friendly】How to Create a Posting Feature (like a Bulletin Board) in Laravel

Add a category_id Column to the posts Table

Run the command to create a migration file for adding a column.

php artisan make:migration add_category_id_to_posts_table

This will generate a new file in database/migrations/. Open the file and modify the up() and down() functions as follows:

public function up(): void
{
    Schema::table('posts', function (Blueprint $table) {
        $table->integer('category_id')
            ->after('title') // Comment out or modify this line if you don’t have a `title` column
            ->nullable();
    });
}

/**
 * Reverse the migrations.
 */
public function down(): void
{
    Schema::table('posts', function (Blueprint $table) {
        $table->dropColumn('category_id');
    });
}

After editing, execute the command to apply the changes.

php artisan migrate

Alternative Method

If your application is not yet in production, you can modify the migration file for the posts table by adding:

$table->integer('category_id')->nullable();

Then reset and reapply migrations using this command:

php artisan migrate:fresh --seed

This approach is more manageable during development when adding new features.

Create a categories Table and Prepare Categories

Create the Categories Table

Run a command to generate a migration file for creating the categories table.

php artisan make:migration create_categories_table

Open the generated file in database/migrations/ and modify it as follows:

public function up(): void
{
    Schema::create('categories', function (Blueprint $table) {
        $table->id();
        $table->string('name'); // Add this column
        $table->timestamps();
    });
}

Execute the following commands to apply the migration and create a model for categories:

php artisan migrate
php artisan make:model Category

Prepare Category Data

Generate a seeder file to create category data.

php artisan make:seeder CategoriesTableSeeder

Edit the newly created file, database/seeder/CategoriesTableSeeder.php, as follows:

use App\Models\Category;

~~~~~

public function run(): void
{
    $categories = ['Category 1', 'Category 2', 'Category 3'];
    foreach ($categories as $category) {
        $c = new Category;
        $c->name = $category;
        $c->save();
    }
}

Add this seeder to database/seeders/DatabaseSeeder.php:

public function run(): void
{
    $this->call([
        CategoriesTableSeeder::class, // Add this line
    ]);
}

Run the seeder to populate the categories table:

php artisan db:seed

Alternatively, use this command to reset and reseed the database:

php artisan migrate:fresh --seed

Create a Save Page Using Prepared Categories

Edit the create method in the controller to send categories to the view.

app/Http/Controllers/PostController.php

use App\Models\Category;
~~~
public function create()
{
    $categories = Category::all();
    return view('post/create', compact('categories'));
}

In views/post/create.blade.php, add the following to create a dropdown for selecting categories:

<form method="POST" action="{{ route('post.store') }}">
  @csrf
  <div>
    <input name="title" />
  </div>
  <div>
    <select name="categoryId">
      @foreach($categories as $category)
      <option value="{{ $category->id }}">{{ $category->name }}</option>
      @endforeach
    </select>
  </div>
  <div>
    <textarea name="content"></textarea>
  </div>
  <button>Submit</button>
</form>

Save the category_id During Submission

Modify the store method in the controller to save the selected category ID.

public function store(Request $request)
{
    $title = $request->title;
    $content = $request->content;
    $categoryId = $request->categoryId;

    $post = new Post;
    $post->user_id = Auth::id();
    $post->title = $title;
    $post->category_id = $categoryId;
    $post->content = $content;
    $post->save();

    return redirect('/');
}

Display Categories Using Relationships

Define Relationships

Add the relationship in the Post model:

app/Models/Post.php

class Post extends Model
{
    public function category()
    {
        return $this->belongsTo(Category::class);
    }
}

Modify the Controller for the Index Page

Edit the index method in the HomeController:

use App\Models\Post;
~~~
function index()
{
    $posts = Post::with('user')
        ->with('category')
        ->orderBy('id', 'desc')
        ->take(10)
        ->get();

    return view('welcome', compact('posts'));
}

Update the View for the Index Page

Display the category name in the view:

@foreach($posts as $post)
<p>{{ $post->category->name }}</p>
@endforeach

With this, you’ve successfully implemented category saving and display.

If any part of this was unclear, please refer to the accompanying video. I hope this is helpful to someone!

Please Provide Feedback
We would appreciate your feedback on this article. Feel free to leave a comment on any relevant YouTube video or reach out through the contact form. Thank you!