Laravel - persistence across multiple models / relationships
I have 3 models: User, Campagin, CampaginType
-
User has a lot of Campagin
-
Campagin is owned by CampaginType
( User not affiliated with CampaginType )
When I save a campaign (contains fields user_id
and campaign_type_id
), how can I save 2 fields with one command.
I try:
$user->campaigns()->campaignType($campaignType)->create($campaignInfo);
But it doesn't work! :(
+3
source to share
1 answer
public function store(Request $request)
{
Campaign::create($request->all());
$campaign = Campaign::where('unique_field', '=', $request->uniquefield)->first();
$campaign->users()->attach($request->user_id);
$campaign->campaign_type()->attach($request->campaign_type_id);
return redirect('your_destination_view');
}
Note
uniquefield
is what is unique to your campaign database table. You should also modify the models by adding appropriate methods to make the relationship eloquent.
-1
source to share