Laravel controller's create function not saving all data - php

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" class="form-control" name="amount" placeholder="Amount" required>
<input type="submit" class="btn btn-xs btn-success ml-2" value="Generate">
</form>
</td>
#endcan
</tr>
#endforeach

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', ...);

Related

I need to fetch my pivot values from many to many relationship data

I have done much research about this but I can't fetch the pivot table as I want.
I want to just fetch the measurement value from the pivot table-like structure you can see. Please check my all details first then you know what I want to show.
Model MeasurementPart.php
public function customers(){
return $this->belongsToMany(Customer::class, 'customer_measurements', 'measurementpart_id', 'customer_id')->withPivot('measurement');
}
Model Customer.php
public function measurementparts(){
return $this->belongsToMany(MeasurementPart::class, 'customer_measurements', 'customer_id', 'measurementpart_id')->withPivot('measurement');
}
Model CustomerMeasurement.php
public function customers(){
return $this->belongsToMany(Customer::class);
}
public function measurementparts(){
return $this->belongsToMany(MeasurementPart::class);
}
Here is my controller CustomerMeasurementController.php
public function editMeasurements(Request $request, $id){
$customer = Customer::with("measurementparts")->find($id);
$clothType = ClothType::all();
return view('customerMeasurements.edit', compact('customer', 'clothType'));
}
public function updateMeasurements(Request $request, Customer $customer){
$measurements = $request->input('measurement');
$filteredmeasurements = array_filter($measurements, function($a){
return $a !== null;
});
$measurement_id = $request->input('measurement_id');
$result = array_combine($measurement_id, $measurements);
$syncData = array();
foreach($result as $measurement_id=> $filteredmeasurements){
$syncData[$measurement_id] = array('measurement' => $filteredmeasurements);
}
$customer->measurementparts()->sync($syncData);
return redirect()->route('customers.index')->withStatus(__('Measurements successfully Updated.'));
}
View EditMeasurements.blade.php
<form action="{{ route('updateMeasurements', ['customer'=> $customer]) }}" method="POST">
#csrf
#foreach ($clothType as $item)
<tr>
<h3>{{ $item->name }}</h3>
<table>
#foreach ($item->measurementparts as $part)
<tr>
<td>
<img style="width: 191px;" class="img"
src="{{ asset('storage/image/' . $part->image) }}" alt="">
<input type="hidden" name="measurement_id[]" value="{{$part->id}}">
</td>
<td>{{ $part->name }}</td>
<td><input type="text" name="measurement[]" value="**I want to put here my measurment value**" class="form-control"></td>
</tr>
#endforeach
</table>
</tr>
<br>
<hr>
#endforeach
<input type="submit" value="Submit" class="btn btn-primary">
</form>
this is the image where I want to put
enter image description here

Laravel 5 ,Table not updating

Im Trying to update my table through Laravel Updation,i get no error when i tried to print the result i just got an null value ,i have pasted my model and controller.
controller
public function update_FAQ_submit()
{
$data = Input::except(array(
'_token'
));
$rule = array(
'faq_ques' => 'required',
'faq_ans' => 'required'
);
$id = Input::get('id');
$validator = Validator::make($data, $rule);
if ($validator->fails()) {
return Redirect::to('Coin_lion/FAQ')->withErrors($validator->messages())->withInput();
} else {
$entry = array(
'faq_ques' => Input::get('faq_ques'),
'faq_ans' => Input::get('faq_ans')
);
$faq=FAQ::update_faq($id, $entry);
return Redirect::to('Coin_lion/manage_FAQ');
}
}
Model
public static function update_faq($id, $entry)
{
return DB::table('faq')->where('id', '=', $id)->update($entry);
}
Routes:
Route::post('Coin_lion/update_FAQ_submit','AdminController#update_FAQ_submit');
my DB
My form
here is my form ,i have included what method i used previously
">
{!! Form::hidden('id', $id) !!}
#foreach ($faq as $info)
<label>Enter your question:</label><br>
<input type="text" class="form-control" name="faq_ques" value="<?php echo $info->faq_ques ?>"><br>
<label>Enter your Answer:</label>
<textarea class="form-control" name="faq_ans" cols="10" rows="5" ><?php echo $info->faq_ans ?></textarea>
<input type="submit" class="btn btn-success" name="submit" value="ADD">
<input type="reset" class="btn btn-danger" name="submit" value="Cancel">
#endforeach
</body>
First try to check that you are getting values in your controller and passing it correctly in you model then you need to replace your query with this. And replace your model code with this.
public function update_faq($id, $entry)
{
DB::table('faq')->where('id',$id)->update($entry);
}
public static function update_faq($id, $entry) {
DB::table('faq')
->where('id', $id) // find your faq by their id
->update($entry); // update the record in the DB.
}

Laravel 5.4 edit post isnt working

Im new in Laravel and i dont understand how to make action forms and routing for editing post
Here is my routes --
Route::post('/menu', 'MenuController#store');
Route::resource('/menu', 'MenuController');
here is controller --
public function update(Request $request, $id)
{
$this->validate($request, [
'menuName' => 'required',
'menuLink' => 'required'
]);
//create new menu
return $id;
// $menus->name = $request->input('menuName');
//$menus->link = $request->input('menuLink');
//$menus->save();
//return redirect('/menu')->with('success', 'Menu updated');
}
Return $id is for check what "id" will give me and he gives me this- "{id}"
here is form --
<form action = "/menu/{id}" method = "POST">
{{ csrf_field() }}
<input name = "_method" type = "hidden" value = "PUT">
<input type="text" id="menuName" name="menuName" class="input-block-level" placeholder="Menu name">
<input type="text" id="linkName" name="menuLink" class="input-block-level" placeholder="Menu link ">
<button type="submit" class="btn btn-success pull-right">Submit</button>
</form>
i am really messed up allready and dont know what i am doing wrong. I cant understand why update funtion returns me "{id}" not value of ID and how can i make this all works
Your are not passing id in your view , you are passing it as a string , u need it create a variable and set it to the right id and pass it to your form.
Change your form action from
action = "/menu/{id}"
to
action = "/menu/".$id"
or you can use laravel blade
Form::open(['route' => ['menu.update', $id]])
and don't forget to close the form at the end
{!!Form::close!!}
You did something wrong with the action attribute. Change it to:
action="/menu/{{ $id }}"
Okay,
you have an edit method which will show the form, that method should return the menu object
public function update($id)
{
// get the menu you wan to edit
$menu = Menu::find($id);
// return the form with the menu object
return view('your.form.view', compact('menu'));
}
Now the form should be like this
// use that object u returned in the form action
<form action = "/menu/{{ $menu->id }}" method = "POST">
{{ csrf_field() }}
<input name = "_method" type = "hidden" value = "PUT">
<input type="text" id="menuName" name="menuName" class="input-block-level" placeholder="Menu name">
<input type="text" id="linkName" name="menuLink" class="input-block-level" placeholder="Menu link ">
<button type="submit" class="btn btn-success pull-right">Submit</button>
</form>
Now the update method should be something like this
public function update(Request $request, $id)
{
$this->validate($request, [
'menuName' => 'required',
'menuLink' => 'required'
]);
// update the data
$bool = Menu::where('id',$id)->update([
'menuName'=> $request->menuName,
'menuLink'=> $request->menuLink,
]);
if(!$bool){
Session::flash('alert','error');
return view('page.index');
}
Session::flash('alert','success');
return view('page.index');
}
This first method is "get" edit that should show the form,
the second is put update that should receive the data from the form(after the show method) and use i to update.
I resolved the error ---
in update blade befor form i added foreach
<div class="container">
<div class="row">
#foreach($menus as $menus)
<form action="/menu/{{$menus->id}}" method="POST">
#endforeach
{{ csrf_field() }}
<input name = "_method" type = "hidden" value = "PUT">
<input type="text" id="menuName" name="menuName" class="input-block-level" placeholder="Menu name">
<input type="text" id="linkName" name="menuLink" class="input-block-level" placeholder="Menu link ">
<button type="submit" class="btn btn-success pull-right">Submit</button>
</form>
</div>
</div>
But now he is editing only 1st post and no matter wich post edit im switching
here is controller --
public function edit($id)
{
$menus = Menu::all();
return view('admin.editmenu')->with('menus', $menus);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'menuName' => 'required',
'menuLink' => 'required'
]);
//create new menu
$menus = Menu::find($id);
$menus->name = $request->input('menuName');
$menus->link = $request->input('menuLink');
$menus->save();
return redirect('/menu')->with('success', 'Menu updated');
}
menu list blade ---
#if(count($menus) > 1)
#foreach($menus as $menus)
<tr>
<th scope="row">1</th>
<td>{{$menus->name}}</td>
<td>{{$menus->link}}</td>
<td>{{$menus->created_at}}</td>
<td>{{$menus->updated_at}}</td>
<td>
<button type = "button"class = "btn btn-outline-danger btn-sm">Delete</button>
<a href = "/menu/{{$menus->id}}/edit" class = "btn btn-outline-warning btn-sm">Edit</button>
</td>
</tr>
#endforeach
#else
Ok ive got it and resolved.
I will start with routes
routes----------
Route::resource('menu', 'MenuController');
that post route was unnecessary, but that didnt affect anything
controller -------
public function edit($id)
{
$menus = Menu::find($id);
return view('admin.editmenu')->with('menus', $menus);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'menuName' => 'required',
'menuLink' => 'required'
]);
//create new menu
$menus = Menu::find($id);
$menus->name = $request->input('menuName');
$menus->link = $request->input('menuLink');
$menus->save();
return redirect('/menu')->with('success', 'Menu updated');
}
Where in edit function i must find ID witch needs to be editing
menu list -----------------
#if(count($menus) > 1)
#foreach($menus as $menu)
<tr>
<th scope="row">1</th>
<td>{{$menu->name}}</td>
<td>{{$menu->link}}</td>
<td>{{$menu->created_at}}</td>
<td>{{$menu->updated_at}}</td>
<td>
<button type = "button"class = "btn btn-outline-danger btn-sm">Delete</button>
<a href = "/menu/{{$menu->id}}/edit" class = "btn btn-outline-warning btn-sm">Edit</button>
</td>
</tr>
#endforeach
#else
<p class = "well"> No menu items created!</p>
#endif
I only changed $menus as $menus on "$menus as $menu" to be clear.
edit blade ------------
#extends('admin.main')
#section('content')
<div class="container">
<div class="row">
<form action="/menu/{{$menus->id}}" method="POST">
{{ csrf_field() }}
<input name = "_method" type = "hidden" value = "PUT">
<input type="text" id="menuName" name="menuName" class="input-block-level" placeholder="Menu name" value="{{ $menus->name }}">
<input type="text" id="linkName" name="menuLink" class="input-block-level" placeholder="Menu link " value="{{ $menus->link }}">
<button type="submit" class="btn btn-success pull-right">Submit</button>
</form>
</div>
</div>
#endsection
Here i deleted #foreach like #Snapey told and added the value option.
I guess value option gave me the errrors all the time.
Thank you all for attention and willing to help! Hope that someday i could help others with my knowledge.

Second independant form inside another form in laravel

I'm trying to make something that I'm not sure if is possible and how exactly can happen.
What I want is to have one table which is in form and one addition form inside. The depending of which button I hit to perform different actions in controller. Here is what I have so far
my blade
{{ Form::open(array('url' => 'admin/inv')) }}
{{ Form::open(array('url' => 'admin/inv/multiPC')) }}
<table class="table table-bordered">
<tbody>
<tr>
<td><input type="checkbox" name="delete[]" value="{{ $product->product_id }}"> </td>
<td><strong>${{ $product->price }}</strong><input type="number" name='price[]' class="form-control"/></td>
</tr>
</tbody>
</table>
<button type="submit" href="{{ URL::to('/admin/del') }}?_token={{ csrf_token() }}">Delete</button>
<button type="submit" href="{{ URL::to('/admin/multiPC') }}?_token={{ csrf_token() }}">Update Price</button>
{{ Form::close() }}
{{ Form::close() }}
Those are both functions
public function pDelete() {
$delete = Input::only('delete')['delete'];
$pDel = Product::whereIn('product_id', $delete)->delete();
return Redirect::to('/admin/inv')->with('message', 'Product(s) deleted.');
}
public function priceUpdate() {
$pchanges->price = Input::only('price')['price'];
$pChange = Product::whereIn('product_id', $pchanges);
$pChange->save();
return Redirect::to('/admin/inv')->with('message', 'Product(s) price changed.');
}
And route
Route::post('/admin/inv', ['uses' => 'AdminController#pDelete', 'before' => 'csrf|admin']);
Route::post ('/admin/inv/multiPC', ['uses' => 'AdminController#priceUpdate', 'before' => 'csrf|admin'])
What happen is when I check product and hit Delete button product is deleted. But when I input price in the input field for price and hit Update Price page only refreshed and price isn't changed.
Is there a way to accomplish this without using JS?
try this type of approach
<form method="POST" class="form-horizontal" action="myapplication/personal">
<input type="number" name='price[]' class="form-control"/>
<input type="checkbox" name="delete[]" value="{{ $product->product_id }}">
<button type="submit" name="step[0]" value="Delete">Delete</button>
<button type="submit" name="step[1]" value="Update">Update Price</button>
</form>
from your controller check the value of step and do as you like
public function formProcess() {
$action = request::get('step'); // i forgot laravel 4 syntex. used laravel 5 instead here :D
if($action == 'Delete')
{
// do delete operation
}
else
{
//do update operation
}
}
hope this helps

Argument 2 passed to Controller method must be in instance of Request, none given

I'm trying to pass 2 dates from one view to another, in my controller, but I get the following error:
Argument 2 passed to App\Http\Controllers\GuestController::reservationToGuest() must be an instance of Illuminate\Http\Request, none given
This is my first view (the view having the date):
<form action="{{ route('create_guest') }}">
{{ csrf_field() }}
<input type="hidden" value="2016-08-26" name="dateOne">
<input type="hidden" value="2016-08-28" name="dateTwo">
<button class="btn btn-block btn-success">Proceed To Check In</button>
</form>
(dateOne and dateTwo are the dates which I want in the second view)
routes.php
Route::get('/guest_page/create/{idreservation?}',[
'uses' => 'GuestController#reservationToGuest',
'as' => 'create_guest'
]);
reservationToGuest in GuestController
public function reservationToGuest($idreservation = null, Request $request){
if($idreservation === null){
return view('guest_page_create', ['idreservation' => 0, 'page_title' => 'Guest Check In', 'check_in_date' => $request['dateOne']]);
} else{ //else clause works just fine and the dates from the database are inserted into the view
$details = DB::table('reservation')
->where('idreservation', $idreservation)
->get();
return view('guest_page_create', ['idreservation' => $idreservation, 'details' => $details, 'page_title' => 'Guest Check In']);
}
}
And in view 'guest_page_create'
<label for="datemask">Check In Date</label>
<input type="date" class="form-control" id="datemask" name="datemask" value="{{ $check_in_date }}">
You shouldn't pass optional parameters before required ones. Try this:
public function reservationToGuest(Request $request, $idreservation = null)
{
// ...
}

Categories