Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

strelok1911's avatar

Can I use one controller to create two rows in two different tables?

Hello.

I am building a web application which has "users" and "profiles". I set up the relationships in my Models and the database is working OK, no errors or such.

In my logic, a user has ONE profile and a profile has ONE user, so it's a one-to-one relationship. In my profiles table, I have the usual "user_id" column.

Now here's my question.

Can I use my UsersController to automatically create a profile when a user is created, and link that profile to the user (via "user_id" column)?

Thanks!

0 likes
3 replies
tykus's avatar

Sure!

Set up the relationships on the relevant models and use the relationship to automatically set the foreign key.

$user = App\User::create([
    //user data
]);

$user->profile()->create([
    // user profile data
]);

return // whatever
1 like
strelok1911's avatar

Hello and thanks for the reply!

I am a total noob when it comes to Laravel (or PHP for that matter) so I will kindly ask of you to explain your answer a bit more in detail.

Here's my current code for the store method:

    $user = new User();
    $profile = new Profile();

    $user->name = $request->name;
    $user->email = $request->email;
    $user->password = $request->password;
    

    $user->save();
    $profile->save();

    return redirect()->route('users');

How would I go about and do this? I need to store "firstname" and "lastname" columns for the profile.

tykus's avatar

In your User model, create a relationship to the Profile model:

class User
{
    protected $fillable = ['name', 'email', 'password']; // mass-assignment protection 

    public function profile() {
        return $this->belongsTo(Profile::class); // user_id is on the profiles table
    }
}

You probably will not be fetching a user through the profile, so the hasOne relationship may not be required:

class Profile
{
    protected $fillable = ['firstname', 'lastname']; // mass-assignment protection 

    public function user() {
        return $this->hasOne(User::class);
    }
}

In your controller, you can utilise this relationship to set the foreign key user_id on the Profile:

public function store(Request $request)
{
    $user = App\User::create([
        'name' => $request->name,
        'email' => $request->email,
        'password' => bcrypt($request->password) // you should hash the password!!
    ]);

    $user->profile()->create([
        'firstname' => $request->firstname,
        'lastname' => $request->lastname,
    ]);
}
1 like

Please or to participate in this conversation.