第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

Laravel 中是否有任何輔助函數(shù)可以將表單數(shù)據(jù)分配到模型中?

Laravel 中是否有任何輔助函數(shù)可以將表單數(shù)據(jù)分配到模型中?

PHP
冉冉說(shuō) 2023-08-26 17:29:29
我知道 laravel 中有一個(gè)resource功能,據(jù)我所知,resource類(lèi)似于jsontomodel及其相反的功能。因此,當(dāng)我處理表單數(shù)據(jù)時(shí),當(dāng)前使用以下自定義幫助器方法。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;}..這個(gè)方法已經(jīng)存在于laravel中嗎?或者類(lèi)似的東西..?
查看完整描述

1 回答

?
料青山看我應(yīng)如是

TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超8個(gè)贊

據(jù)我所知,Laravel 中沒(méi)有“標(biāo)準(zhǔn)”方法可以完成上面的操作,如果輸入缺失,則為輸入分配默認(rèn)值,并控制使用map.

我相信,最接近您正在尋找的東西是批量分配。

有許多不同的方法和模式來(lái)處理這些類(lèi)型的請(qǐng)求,您的方法對(duì)我來(lái)說(shuō)似乎很好。我個(gè)人使用Form Requests?+?DTO,因?yàn)榇a本身文檔記錄得很好。舉個(gè)例子:

控制器:

class UsersController extends Controller

{

? ? ...


? ? public function store(CreateUserRequest $request)

? ? {

? ? ? ? $user = User::create($request->toCommand());


? ? ? ? // Return response however you like

? ? }


? ? ...

}

表單請(qǐng)求


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??

}

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());

? ? }

}

這是一種相當(dāng)“Laravel 方式”的做事方式,代碼本身向需要使用它的任何其他人(以及稍后的你:D)傳達(dá)了大量信息。


查看完整回答
反對(duì) 回復(fù) 2023-08-26
  • 1 回答
  • 0 關(guān)注
  • 166 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)