Home > Back-end >  How to make default request values inside $validated array in Laravel?
How to make default request values inside $validated array in Laravel?

Time:01-04

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),
    ]);

CodePudding user response:

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.

CodePudding user response:

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)
    ]);
  • Related