college-courses/app/Filament/Resources/UserResource.php

97 lines
3.1 KiB
PHP
Raw Permalink Normal View History

2024-10-15 10:15:40 +03:00
<?php
namespace App\Filament\Resources;
use App\Filament\Resources\UserResource\Pages;
use App\Models\Role;
use App\Models\User;
use Filament\Forms;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Form;
use Filament\Resources\Resource;
use Filament\Resources\Table;
use Filament\Tables;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Hash;
class UserResource extends Resource
{
protected static ?string $model = User::class;
protected static ?string $navigationIcon = 'heroicon-o-collection';
public static function form(Form $form): Form
{
return $form
->schema([
//
TextInput::make('name')->label('Логин')
->required(),
TextInput::make('password')->label('Пароль')
->password()
->dehydrateStateUsing(fn ($state) => Hash::make($state))
->dehydrated(fn ($state) => filled($state))
->required(fn (string $context) => $context === 'create'),
Select::make('role')->label('Роль')->default('student')->options([
'student' => 'Студент',
'author' => 'Педагог',
'admin' => 'Админ',
])->required(),
]);
}
public static function table(Table $table): Table
{
return $table
->columns([
TextColumn::make('name')->label('Логин'),
TextColumn::make('role.name')->label('Роль')
//
])
->filters([
SelectFilter::make('role')->label('Роль')
->options([
'student' => 'Студент',
'author' => 'Педагог',
'admin' => 'Админ',
])->attribute('role')
])
->actions([
Tables\Actions\EditAction::make()
->using(function (Model $record, array $data): Model {
if (array_key_exists('password', $data)) {
$data['password'] = $data['password'];
}
$role_id = Role::where('name', $data['role'])->first()->id;
$data = array_merge($data, ['role_id' => $role_id]);
$record->update($data);
return $record;
}),
Tables\Actions\DeleteAction::make()->requiresConfirmation(),
])
->bulkActions([
Tables\Actions\DeleteBulkAction::make(),
]);
}
public static function getRelations(): array
{
return [
//
];
}
// public function
public static function getPages(): array
{
return [
'index' => Pages\ManageUsers::route('/'),
];
}
}