Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/242.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在laravel中是否有任何辅助函数将表单数据分配到模型中?_Php_Laravel - Fatal编程技术网

Php 在laravel中是否有任何辅助函数将表单数据分配到模型中?

Php 在laravel中是否有任何辅助函数将表单数据分配到模型中?,php,laravel,Php,Laravel,我知道laravel中有一个resource功能,据我所知resource类似于jsontomodel及其反面 因此,当我处理表单数据时,当前使用以下自定义帮助器方法 public function assignFormdata(Request $request, $model, $map = []) { foreach($map as $input=>$field) { // $field is model's param. $input is form data

我知道laravel中有一个
resource
功能,据我所知
resource
类似于
json
to
model
及其反面

因此,当我处理表单数据时,当前使用以下自定义帮助器方法

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;
}
。。此方法是否已存在于laravel中?或者类似的东西。

据我所知,Laravel中没有一种“标准”方法可以实现上述功能,即在输入缺失时为其指定默认值,并使用
映射控制设置哪些属性

我相信,最接近你所寻找的东西是

有许多不同的方法和模式来处理这些类型的请求,我觉得您的方法很好。我个人使用+是因为代码很好地记录了自己。例如:

控制器:

class UsersController extends Controller
{
    ...

    public function store(CreateUserRequest $request)
    {
        $user = User::create($request->toCommand());

        // Return response however you like
    }

    ...
}
格式请求

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'),
            ...
        ]);
    }
}
命令DTO

class CreateUserCommand extends DataTransferObject
{
    /** @var string */
    public $name;

    /** @var \Carbon\Carbon */
    public $birthdate;

    /** @var string */
    public $role = 'employee'; // Sets default to employee

    /** @var null|string */
    public $gender;            // Not required  
}

这是一种相当“Laravel”的处理方式,代码本身向需要使用它的任何其他人(以及您以后的用户)传达了大量信息。

您能否重新表述问题,并添加您需要的帮助?谢谢
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());
    }
}