Ahmadnoori's avatar

How to add ->index() on enum('draft', 'pending', 'published')

I have 200k+ posts and I want to get all posts that are published. I have also applied pagination with a limit 20

$table->enum('status', ['draft','pending_review','published','trash']);

this is my column schema. How to index the status column that are published? Should I use:

$table->enum('status', ['draft','pending_review','published','trash'])-index();

Please guide I hope you got my point

0 likes
2 replies
sr57's avatar

How to index the status column that are published?

You index columns (status in your example) and then sql run faster queries. if after you want to work with an extract ie status='published' you can use scope

https://laravel.com/docs/8.x/eloquent#query-scopes

PS : you can also create a sql view to work on but it's not the "Laravel way".

manojo123's avatar

the ->index() It's the way to say to the Laravel Migration to add indices to that column, in order to get faster results when searching through that particular column. It's a common procedure in DB design when building tables. Just "index" some particular columns if you plan to make searchs in the table using those columns.

Reference: https://stackoverflow.com/questions/37350263/what-does-index-mean-in-laravel

About enums: You can create a enum class (There no specific place for them. I like to create the app folder)

<?php 

namespace App\Enums;

enum PostStatus : string
{
    case Draft = 'draft';
    case PendingReview = 'pending_review';
    case Published = 'published';
    case Trash = 'trash';
}

Then at your post Model you add the cast for enum field

protected $casts = [
    'status' => PostStatus::class
];

And finally you will be able to use your model with the enum values with the syntax:

$post->status->value;
$post->status = PostStatus::Published;
2 likes

Please or to participate in this conversation.