Issue
On the store() method of a model, I want to save two more models. I need the id of the current model that I am storing. How can I get that?
Controller
public function store(Request $request, Property $property)
{
/*******************************************************
* Validation sent data
* Validate e forme ersali user
*******************************************************/
$data = $request->validate([
'type' => 'required',
'title' => 'required',
'description' => 'required',
'base_capacity' => 'required',
'max_occupancy' => 'required',
]);
Property::create($data);
PropertyDetail::create([
'property_id' => 1,
'state' => $request->state,
'city' => $request->city,
'address' => $request->address,
'post_code' => $request->post_code,
'placearea' => $request->place_area,
'telephone' => $request->telephone,
]);
}
Here I hard-coded the property id in the property detail. However, I want to get the id of the current property I just created above that.
Solution
Ok-ish approach
- Create an instance of
Property
$property = Property::create($data);
- Reference it
PropertyDetail::create([
'property_id' => $property->id, // here it is
'state' =>$request->state,
'city' =>$request->city,
'address' =>$request->address,
'post_code' =>$request->post_code,
'placearea' =>$request->place_area,
'telephone' =>$request->telephone,
]);
Safer approach
Safer approach is nearly identical, except you're using two queries and queries can fail. You want to make sure that either both succeed or none succeeds. For that, we use transactions.
What we're making safe about is ensuring data got to the database.
public function store(Request $request,Property $property)
{
/*******************************************************
* Validation sent data
* Validate e forme ersali user
*******************************************************/
$data = $request->validate([
'type' => 'required',
'title' => 'required',
'description' => 'required',
'base_capacity' => 'required',
'max_occupancy' => 'required',
]);
\DB::transaction(function() use ($data, $request) {
$property = Property::create($data);
PropertyDetail::create([
'property_id' => $property->id,
'state' =>$request->state,
'city' =>$request->city,
'address' =>$request->address,
'post_code' =>$request->post_code,
'placearea' =>$request->place_area,
'telephone' =>$request->telephone,
]);
});
}
Answered By - Mjh Answer Checked By - Marie Seifert (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.