Courses

Filament 3 From Scratch: Practical Course

Select Dropdown with/without belongsTo

You're reading a FREE PREVIEW of a PREMIUM course.
Summary of this lesson:
- Implementing select dropdowns
- Creating radio button alternatives
- Managing belongsTo relationships in forms
- Handling relationship data in tables

Video Version of the Lesson

[Only for premium members]

Link to the repository

[Only for premium members]

Text Version of the Lesson

In this lesson, let's review one of the most popular field types used in forms: dropdown selects. The data for the options may or may not come from another DB table as a relationship.

We will add two fields to our Products form:

  • select to choose product status: "in stock", "sold out", "coming soon"
  • select to choose product category: from another Category model

Simple Select Dropdown

Let's say that product may have one of the defined statuses, but we don't want to save them in a separate table.

Instead, let's make a PHP Enum class with values:

php artisan make:enum Enums/ProductStatusEnum --string

app/Enums/ProductStatusEnum.php:

namespace App\Enums;
 
enum ProductStatusEnum: string
{
case IN_STOCK = 'In Stock';
case SOLD_OUT = 'Sold Out';
case COMING_SOON = 'Coming Soon';
}

Then, we will have a string field in the database with the default value from that Enum, in a new Migration:

Database Migration:

use App\Enums\ProductStatusEnum;
 
// ...
 
return new class extends Migration
{
public function up(): void
{
Schema::table('products', function (Blueprint $table) {
$table->string('status')
->default(ProductStatusEnum::IN_STOCK->value);
});
}
};

Let's make this field fillable in the Product Model.

app/Models/Product.php:

class Product extends Model
{
use HasFactory;
 
protected $fillable = ['name', 'price', 'status'];
}

And then, we can show the value in the table, just as a simple column:

app/Filament/Resources/ProductResource.php:

return $table
->columns([
Tables\Columns\TextColumn::make('name')
->sortable(),
Tables\Columns\TextColumn::make('price')
->sortable()
->money('usd')
->getStateUsing(function (Product $record): float {
return $record->price / 100;
}),
Tables\Columns\TextColumn::make('status'),
])

In the form, we add that field as...

The full lesson is only for Premium Members.
Want to access all 24 video+text lessons of this course? (2 h 01 min)

You also get:

  • 78 courses
  • Premium tutorials
  • Access to repositories
  • Private Discord