I know that there is a resource
functionality in laravel and as far as I know resource
is something like json
to model
and its reverse..
So when I process form data, currently, use following custom helper method..
public function assignFormdata(Request $request, $model, $map = []) { foreach($map as $input=>$field) { // $field is model's param. $input is form data key. $model->$field = $request->input($input) ?? $field; } return $model; }
.. Is this method already exist in laravel? or something similar..?
Advertisement
Answer
There is no “standard” way in Laravel, that I am aware of, that will accomplish what you have above, where you assign a default value to an input if it is missing, and control what attributes are being set using the map
.
The closest thing to what you are looking for is Mass Assignment, I believe.
There are many different methods and patterns to handle these types of requests, and your approach seems fine to me. I personally use Form Requests + DTO because the code documents itself quite well. As an example:
Controller:
class UsersController extends Controller { ... public function store(CreateUserRequest $request) { $user = User::create($request->toCommand()); // Return response however you like } ... }
FormRequest
class CreateUserRequest extends FormRequest { ... public function rules() { // Validate all the data here } ... public function toCommand() : CreateUserCommand { return new CreateUserCommand([ 'name' => $this->input('name'), 'birthdate' => Carbon::parse($this->input('birthdate')), 'role' => $this->input('role'), 'gender' => $this->input('gender'), ... ]); } }
Command DTO
class CreateUserCommand extends DataTransferObject { /** @var string */ public $name; /** @var CarbonCarbon */ public $birthdate; /** @var string */ public $role = 'employee'; // Sets default to employee /** @var null|string */ public $gender; // Not required }
class User extends Model { ... protected $fillable = [ 'name', 'birthdate', 'role', 'gender', ]; ... public static function create(CreateUserCommand $command) { // Whatever logic you need to create a user return parent::create($command->toArray()); } }
That is a fairly “Laravel way” of doing things, and the code itself conveys a lot of information to anyone else (and you later :D) who needs to use it.