Daniel-Pablo's avatar

help refactoring this code is easy,,,,

hi I git this code and want to know how I can make it shorter

        $newUser = User::create([
            'name' => $request->userName,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);

        $newUser->profile()->create();
        $newUser->wallet()->create();
        $newUser->rank()->create();
        $newUser->table1()->create();
        $newUser->table2()->create();
        $newUser->table3()->create();
...
...
... more tables to instantiate and create

I got a New User-created then got to create the relation tables and there are like 20 tables can this be encapsulated on a function or a callback? maybe under something like this

        $newUser->create([
profile(),
wallet(),
rank(),
]);

thanks in Advance

0 likes
8 replies
Daniel-Pablo's avatar

thanks, Michal, I can change USER but still will be the same, can it be refactorized or shortened the code, or I am right now with the shortest solution? thanks

MichalOravec's avatar

Yes, you are.

But you can do for example instead of

$user->profile()->create([
    'twitter' => $request->twitter,
    'facebook' => $request->facebook,
    // etc
]);

do this

<input type="text" name="profile[twitter]"> 

<input type="text" name="profile[facebook]"> 
$user->profile()->create($request->profile);

Of course don't forget to add a validation.

And in this case you need to validate an array

https://laravel.com/docs/8.x/validation#validating-arrays

wingly's avatar

You are creating all those relationships with no data ?

MichalOravec's avatar

If you only want to create relationships with no data then

$relationships = [
    'profile', 'wallet', 'rank',
    'table1', 'table2', 'table3', 
    // etc
];

foreach ($relationships as $relationship) {
    $user->{$relationship}()->create();
}
wingly's avatar

Exactly what i had in mind

$user = User::create([
    'name' => $request->userName,
    'email' => $request->email,
    'password' => Hash::make($request->password),
]);

collect([ 'profile', 'wallet', 'etc'])
    ->each(function ($relation) use ($user) {
        $user->{$relation}()->create();
    });
Daniel-Pablo's avatar

thank you very much both @michaloravec and @wingly thanks for your help this is what I expect to get and understand with the question of the topic

@michaloravec can you please explain to me what means this

$user->{$relationship}()->create(); in this code there is the relationship inside a bracket {$relationship}

what means that... It's the first time I see something like that...

Please or to participate in this conversation.