I am trying to save this "code" attributes into my codes table along with the "gift_card_id", but only the first one is saved.
- When I call the dd($giftCard), it shows me the model info itself, not an object from it. and when I dd($giftCard->id), it gives me null.
- When I add ($id) to my function parameters "public function generateCodes(Request $request, GiftCard $giftCard, $id)", and change the create function to "$giftCard->codes()->create(['code' => $code, 'gift_card_id' => $id]);" and call dd($id), it shows the right id.
In both of the above, the data get stored excpt the "gift_card_id".
web.php
Route::post('gift-cards/{giftcard}/add-codes', 'GiftCardController@generateCodes')->name('gift-cards.generateCodes');
GiftCardController.php
public function generateCodes(Request $request, GiftCard $giftCard) {
$request->validate([
'amount' => 'required|integer|min:1',
]);
if ($request->input('amount') > 0) {
do {
$codes = [];
for ($i = 0; $i < $request->input('amount'); $i ) {
$codes[] = (string)mt_rand(pow(10, 10), pow(10, 11) - 1);
}
$codesUnique = Code::whereIn('code', $codes)->count() == 0;
} while (!$codesUnique);
foreach ($codes as $code) {
// dd($id);
$giftCard->codes()->create(['code' => $code]);
}
}
View.blade.php
@foreach($giftCards as $key => $giftcard)
<tr data-entry-id="{{ $giftcard->id }}">
<td> {{ $giftcard->name ?? '' }} </td>
<td> {{ $giftcard->price ?? '' }} </td>
<td> {{ $giftcard->codes_count ?? '' }} </td>
@can('gift_card_create')
<td>
<form action="{{route('gift-cards.generateCodes', $giftcard->id)}}" method="POST">
@csrf
<input type="number" name="amount" placeholder="Amount" required>
<input type="submit" value="Generate">
</form>
</td>
@endcan
</tr>
@endforeach
CodePudding user response:
You need to have the type-hinted parameter name on the route action match the name of the route parameter if you want Explicit Route Model Binding to take place. If you don't match these you are just defining dependencies that the method needs which would cause Dependency Injection to happen. You can change the route parameter name or the name of the parameter for the method so they match:
Route::post('gift-cards/{giftCard}/add-codes', ...);