45 lines
1.3 KiB
PHP
45 lines
1.3 KiB
PHP
<?php
|
|
|
|
namespace App\Actions\Students;
|
|
|
|
use App\Exceptions\AuditionAdminException;
|
|
use App\Models\Student;
|
|
use Arr;
|
|
|
|
class CreateStudent
|
|
{
|
|
public function __construct()
|
|
{
|
|
}
|
|
|
|
/**
|
|
* @throws AuditionAdminException
|
|
*/
|
|
public function __invoke(array $newData): Student
|
|
{
|
|
|
|
// $newData[] must include keys first_name, last_name, grade - throw an exception if it does not
|
|
foreach (['first_name', 'last_name', 'grade'] as $key) {
|
|
if (! Arr::has($newData, $key)) {
|
|
throw new AuditionAdminException('Missing required data');
|
|
}
|
|
}
|
|
|
|
if (! Arr::has($newData, 'school_id')) {
|
|
$newData['school_id'] = auth()->user()->school_id;
|
|
}
|
|
if (Student::where('first_name', $newData['first_name'])->where('last_name', $newData['last_name'])
|
|
->where('school_id', $newData['school_id'])->exists()) {
|
|
throw new AuditionAdminException('Student already exists');
|
|
}
|
|
|
|
return Student::create([
|
|
'first_name' => $newData['first_name'],
|
|
'last_name' => $newData['last_name'],
|
|
'grade' => $newData['grade'],
|
|
'school_id' => $newData['school_id'],
|
|
'optional_data' => $newData['optional_data'] ?? null,
|
|
]);
|
|
}
|
|
}
|