简体   繁体   中英

How to make default request values inside $validated array in Laravel?

Controller code:

public function store(UserStoreRequest $request) {

$validated = $request->validated();

$validated['user_type_id'] = 2;
$validated['user_gender_id'] = $request->user_gender_id;
$validated['last_login_at'] = Carbon::now();
$validated['password'] = Hash::make($request->password);

User::create($validated);

return to_route('all-users'); 
}

Is there a better way to do this?

I tried something like this but didn't work:

     $validated = $request->validated([
        'user_type_id' => 2,
        'user_gender_id' => $request->user_gender_id,
        'last_login_at' => Carbon::now(),
        'password' => Hash::make($request->password),
    ]);

there is not official laravel way to do this but you could make most of those values default in a migration.

you could also clean up the controller a little bit by doing something like this.

public function store(UserStoreRequest $request) {

    User::create([
      ...$request->validated(), 
      'user_gender_id' => $request->user_gender_id;
      'password' => Hash::make($request->password)
    ]);

    return to_route('all-users'); 
}

And then for the default values you can do this in your migration

Schema::create('flights', function (Blueprint $table) {
    $table->foreignId('user_type_id')
        ->nullable()
        ->default(2)
        ->constrained();
});

and then lastly to cast the last_login_at to a now by default you can do that a few ways but using a mutator on the model is probably the best.

I did like this:

 User::create([
        ...$request->validated(), 
        'last_login_at' => now(),
        'user_type_id' => 2,
        'password' => Hash::make($request->password)
    ]);

If you store some images do something like this:

  $validated = $request->validated();

   if($request->hasFile('photo')) { ..etc
   $validated['photo'] = $filename; 
   }

      User::create([
        ...$validated, 
        'last_login_at' => Carbon::now(),
        'user_type_id' => 2,
        'password' => Hash::make($request->password)
    ]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM