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

Varsang's avatar

Create form with relationship model/table

I have search a lot on the topic of form binding relationship but couldn’t successfully apply it.

I have 3 tables.

  1. Profile
  2. Family
  3. Preferences.

Profile -> family = one to one relationship Profile -> preferences = one to many relationship.

I got all the relationships working. Tested it all in tinker and works perfectly.

The profile - family font works fine cause I have one form/submit and it populated both based on family->profile_id = profile->id (last inserted id).

My problem is how can I get the profile id when creating the perefences form? I need to get the profile id in order to store in the preferences table. Is there a way I can get the url in the following order and then get the id?

/profile/1/preference/create

0 likes
2 replies
biishmar's avatar

you already have profile id in url...

get url by request function

$url = request()->url();
$splitedUrl = explode('profile/', $url);
$id = explode('/preference', $splitedUrl[1])[0];

by this code u will get profile id from url

arthurvillar's avatar
Level 9

If you did your relations correctly, you probably have something like this set up now

class Profile extends Model
{
    public function family()
    {
        return $this->belongsTo(Family::class);
    }

    public function preference()
    {
        return $this->hasMany(Preference::class);
    }
}

class Family extends Model
{
    public function profile()
    {
        return $this->hasMany(Profile::class);
    }
}

class Preference extends Model
{
    public function profile()
    {
        return $this->belongsTo(Profile::class);
    }
}

Side note: can't multiple profiles share the same preferences? The way you indicated means that each profile have unique preferences...

You can now pass any of these relationships into your route, like so

Route::post('/profiles/{profile}/{family}/preference/create', 'PreferenceController@store');

This is what your controller will look like

public function store(Request $request, Profile $profile, Family $family)
{    

    Preference::create([
    'profile_id' => $profile->id,
    'colum_name_1' => $request->column_name_1,
    'colum_name_2' => $request->column_name_2,
    ]);

    return redirect('your-redirect-path-here');
}

Please or to participate in this conversation.