Video Version of the Lesson
[Only for premium members]
[Only for premium members]
[Only for premium members]
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:
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...