I'm trying to add data to my cart table by adding a product to cart but instead i get the above error Undefined index:size
code from the responsible controller
public function addToCart(Request $request){
Session::forget('CouponAmount');
Session::forget('CouponCode');
$data = $request->all();
if(empty($data['user_email'])){
$data['user_email']='';
}
$session_id= Session::get('session_id');
if(empty($session_id)){
$session_id = str_random(40);
Session::put('session_id', $session_id);
}
$sizeArr=explode("-",$data['size']);
$countProducts = DB::table('cart')-
>where(['product_id'=>$data['product_id'],
'product_color'=>$data['product_color'],
'size'=>$sizeArr[1], 'session_id'=>$session_id,])->count();
if($countProducts>0){
return redirect()->back()->with('flash_message_error', 'Exact
product already exists in Cart!');
}else {
$getSKU = ProductsAttribute::select('sku')-
>where(['product_id'=>$data['product_id'], 'size'=>$sizeArr[1]])-
>first();
DB::table('cart')->insert(['product_id'=>$data['product_id'],
'product_name'=>$data['product_name'],
'product_code'=>$getSKU->sku,
'product_color'=>$data['product_color'], 'price'=>$data['price'],
'size'=>$sizeArr[1], 'quantity'=>$data['quantity'],
'user_email'=>$data['user_email'], 'session_id'=>$session_id,]);
}
return redirect('cart')->with('flash_message_success', 'Product has
been added to cart!');
}
the blade file where size is input
<h1>{{ $productDetails->product_name }}</h1>
<p>{{ $productDetails->description }}</p>
<div class="dropdown_top">
<div class="dropdown_left">
<select id="size" class="dropdown" tabindex="10"
data-settings='{"wrapperClass":"metro1"}'>
<option value="0">Select size</option>
#foreach ($productDetails->attributes as
$sizes)
<option value="{{ $productDetails->id }}-
{{ $sizes->size }}">{{ $sizes->size }}
</option>
#endforeach
</select>
</div>
instead of being redirected to my cart page I get Undefined index:size
I added this in a comment, but thought I'd eloborate :)
The $request->all() call isn't returning 'size' because the name attribute is missing from your <select> tag in the template. The following should fix it:
<select name="size" id="size" class="dropdown" tabindex="10" data-settings='{"wrapperClass":"metro1"}'>
Related
I'm getting this error: Undefined variable: sales_rep_names (View: C:\wamp64\www\VLCMRenewals\resources\views\search\index.blade.php)
when I try adding a new search dropdown in my blade. This is the new code I've added that's causing the problem:
{{--select Sales Representative --}}
<!-- adding sales rep placeholder
Can we make this a drop-down menu?
need to make sure "name=" is correct -->
<div class="form-group col-md-4">
<label class="mr-sm-2" >Sales Representative</label>
<select class="custom-select mr-sm-2" name="primary_sales_rep">
<option selected></option>
#if(count($sales_rep_names) >0)
#foreach ($sales_rep_names as $sales_rep_name)
<option value='{{$sales_rep_name->Primary_Sales_Rep}}'>{{$sales_rep_name->Primary_Sales_Rep}}</option>
#endforeach
#endif
</select>
</div>
And here's an example of a dropdown that DOES work (I copied the format):
{{--select Manufacturer --}}
<div class="form-group col-md-4" >
<label class="mr-sm-2" >Manufacturer Name</label>
<select class="custom-select mr-sm-2" name="company">
<option selected></option>
#if(count($manufacturer_names) >0)
#foreach ($manufacturer_names as $manufacturer_name)
<option value='{{$manufacturer_name->Manufacturer_Name}}'>{{$manufacturer_name->Manufacturer_Name}}</option>
#endforeach
#endif
</select>
</div>
Lastly, here's the code I have my in Controller (manufacturer and customer both work):
public function index()
{
// will need to add Sales Rep here
$customer_names = DB::table('dbo.contract_view')
->distinct()
->orderBy('Customer_Name','asc')
->get(['Customer_Name']);
$manufacturer_names = DB::table('dbo.contract_view')
->distinct()
->orderBy('Manufacturer_Name','asc')
->get(['Manufacturer_Name']);
// when I tested with product part number it also gave me an error with index.blade.php. maybe this is the wrong spot?
$sales_rep_names = DB::table('dbo.contract_view')
->distinct()
->orderBy('Primary_Sales_Rep','asc')
->get(['Primary_Sales_Rep']);
return view('search.index', ['customer_names' => $customer_names], ['manufacturer_names' => $manufacturer_names], ['sales_rep_names' => $sales_rep_names]);
}
Any advice?
You are sending the variables as 3 different arrays separated by commas. The view parameters are $view, $data, $mergeData, so the forth parameter you are sending is ignored.
The correct way to pass variables to the view is like this:
return view('search.index', [
'customer_names' => $customer_names,
'manufacturer_names' => $manufacturer_names,
'sales_rep_names' => $sales_rep_names
]);
or
return view('search.index')
->with(compact('customer_names', 'manufacturer_names', 'sales_rep_names');
or
return view('search.index')
->with('customer_names', $customer_names)
->with('manufacturer_names', $manufacturer_names)
->with('sales_rep_names', $sales_rep_names)
So my problem is that if i try to save only one value like "Location in the layout" of a post it works, but the moment i am saving an array I'm getting something like ["value 1" , "value 2"] in the DB, therefore it cant be read and in the CRUD-Controller there is no data saved when i am editing.everything works perfectly except the value i am getting from the data. I would appreciate any help, methods or alternatives
edit.blade.php
<div class="form-group">
<label>Select Post Location</label>
<select
class="form-control select2 select2-hidden-accessible"
multiple=""
data-placeholder="Select Locations"
style="width: 100%"
tabindex="-1"
aria-hidden="true"
name="post_locations[]"
id="post_locations"
>
<option value="TopBox-GR" #if ($post->post_locations == "TopBox-GR") selected #endif>TopBox-GR</option>
<option value="TopBox-C3" #if ($post->post_locations == "TopBox-C3") selected #endif>TopBox-C3</option>
<option value="TopBox-C4" #if ($post->post_locations == "TopBox-C4") selected #endif>TopBox-C4</option>
</select>
</div>
home controller
public function index()
{
$posts = post::where([['status',1], ['post_locations','TopBox-GR']])->get();
return view('user.blog',compact('posts'));
}
and view:
<div class="topbox-c4">
#foreach ($posts as $post)
<a href="{{ route('post',$post->slug) }}">
<div class="image-topbox-c4-container">
<img src="{{ Storage::disk('local')->url($post->image)}}" />
</div>
<div class="text-topbox-c4-container">
<h3>{{$post->title}}</h3>
<p>
{{$post->subtitle}}
</p>
</div>
</a>
#endforeach
</div>
post.controller:
public function update(Request $request, $id)
{
$this->validate($request,[
'title'=>'required',
'subtitle'=>'required',
'slug'=>'required',
'body'=>'required',
'image'=>'required',
'post_locations'=>'required',
]);
if($request->hasFile('image'))
{
$imageName = $request->image->store('public');
}
$post = post::find($id);
$post->image = $imageName;
$post->title = $request->title;
$post->subtitle = $request->subtitle;
$post->slug = $request->slug;
$post->post_locations = $request->post_locations;
$post->body = $request->body;
$post->status = $request->status;
$post->tags()->sync($request->tags);
$post->categories()->sync($request->categories);
$post->save();
return redirect(route('post.index'));
}
Firstly you should get selected locations in $selectLocations variable and all locations in $allLocations variable for edit.blade.php
In edit.blade.php, you can display like this:-
#foreach($selectLocations as $value)
<select class="form-control" name="post_locations[]" multiple=''>
<option value="">Select Location</option>
#foreach($allLocations as $val)
<option #if($value['id'] == $val->id) {{ 'selected' }} #endif value="{{ $val->id }}">{{ $val->name}}</option>
#endforeach
</select>
#endforeach
I have multiple select box with same name inside loop in a form. I have added laravel validation to check select box selected or not. But validation error message is showing for all the select boxes. Please check image attached. Any help would be appreciated.
cart.blade.php
#forelse($carts as $key => $cart)
<div class="col-sm-4 col-sm-4-booking1 form-group {{ $errors->has('guest.*.sleeps') ? ' has-error' : '' }}">
<label>Sleep(s)</label>
<select class="form-control form-control-booking1 jsBookCalSleep" name="guest[{{ $cart->_id }}][sleeps]">
<option value="">Choose Sleep(s)</option>
#for($i = 1; $i <= 30; $i++)
<option value="{{ $i }}" #if($i == $cart->sleeps) selected #endif>{{ $i }}</option>
#endfor
</select>
#if ($errors->has('guest.*.sleeps'))
<span class="help-block"><strong>{{ $errors->first('guest.*.sleeps') }}</strong></span>
#endif
</div>
#empty
<p>No bookings in your cart</p>
#endforelse
CartController.php
public function store(CartRequest $request)
{
dd($request->all());
}
CartRequest.php
public function rules()
{
return [
'guest.*.sleeps' => 'required|not_in:0'
];
}
Try these
#php
$inputName='guest.'.$cart->_id.'.sleeps';
#endphp
#if ($errors->has($inputName))
<span class="help-block"><strong>{{ $errors->first($inputName) }}</strong></span>
#endif
I didn't tested it,
If not working let me know
Solution: We can solve this issue by using two function. a.collect and b. contains. See the example below.
<select class="form-control m-bootstrap-select m_selectpicker"
name="generic_ids[]" data-live-search="true" multiple>
<option value="">Select Generic</option>
#foreach($generics as $generic)
<option value="{{$generic->id}}"
#if(collect(app()->request->generic_ids)->contains($generic->id))
selected
#endif
>{{$generic->title}}</option>
#endforeach
</select>
Code
Output
I have a view show.php of my single product, when user click on ADD PRODUCT my controller CartController.php update my session cart and update my cartSession table,
Now i'm tryng to put new data (Color input,Size input, Quantity input) on my session and also in my CartSession table. But i dont know why it doesn't work.
-I think that the principal problem is that $request->get('input') doesn't pass to my CartController.php , i tried to return
$request->all() and there is not nothing.
CartController.php
namespace dixard\Http\Controllers;
use Illuminate\Http\Request;
use dixard\Http\Requests;
use dixard\Http\Controllers\Controller;
use dixard\Product;
use dixard\CartSession;
use dixard\CartItem;
use dixard\Shipping;
use Session;
// i think that all classes are ok
public function add(Product $product, CartSession $CartSession,Request $request)
{
$id = $request->get('id');
$cart = \Session::get('cart');
$product->quantity = $request->get('qty');
$product->size = $request->get('size');
$product->color = $request->get('color');
$cart[$product->id] = $product;
\Session::put('cart', $cart);
return $request->all(); // here i tried to get all inputs but it shows me nothing result
$subtotal = 0;
foreach($cart as $producto){
$subtotal += $producto->quantity * $producto->price;
}
$session_code = Session::getId();
$CartSession = new CartSession();
$session_exist = CartSession::where('session_code', $session_code)->orderBy('id', 'desc')->first();
if (isset($session_exist)) {
$s = new CartSession;
$data = array(
'subtotal' => $subtotal,
);
$s->where('session_code', '=', $session_code)->update($data);
}else {
$CartSession = new CartSession();
$CartSession->session_code = $session_code;
$CartSession->subtotal = $subtotal;
$CartSession->save();
}
//return $cart;
//salveremo tutte le informazioni nel array cart nella posizione slug
foreach($cart as $producto){
$this->saveCartItem($producto, $CartSession->id, $session_code, $cart);
}
return redirect()->route('cart-show');
}
Routes.php
Route::bind('product', function($id) {
return dixard\Product::where('id', $id)->first();
});
Route::get('cart/add/{product}', [
'as' => 'cart-add',
'uses' => 'CartController#add'
]);
show.php view
Get Data about the product is ok, title, description, color avaible, price ecc. all information pass to my view.
{!! Form::open(['route'=> ['cart-add', $product->id],'class'=>'form-horizontal form-label-left'])!!}
<input type="hidden" name="_method" value="PUT">
<input type="hidden" name="id" value="{{$product->id}}">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="p_color">Colore</label>
<select name="color" id="p_size" class="form-control">
#foreach($colors as $color)
<option value="{{ $color->color }}">{{ $color->color }}</option>
#endforeach
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="size">Size</label>
<select name="size" id="p_size" class="form-control">
<option value="XS">XS</option>
<option value="S">S</option>
<option value="M">M</option>
<option value="L">L</option>
<option value="XL">XL</option>
</select>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="qty">Quantity</label>
<select name="qty" id="p_qty" class="form-control">
<option value="">1</option>
<option value="">2</option>
<option value="">3</option>
</select>
</div>
</div>
</div>
<div class="product-list-actions">
<span class="product-price">
<span class="amount">{{$product->price}}</span>
<input type="submit" class="btn btn-lg btn-primary" >
ADD PRODUCT
</input>
</div><!-- /.product-list-actions -->
{!! Form::close() !!}
Thank you for your help!
You have to explicitly set the post-method to be "get" or you need to change your router to accept the request as post. Even though you're calling the route by name, Form::open defaults to "POST"
https://laravelcollective.com/docs/5.2/html#opening-a-form
Option 1. Change
Route::get('cart/add/{product}',...
to
Route::post('cart/add/{product}',...
Option 2. Change
{!! Form::open(['route'=> ['cart-add', $product->id],'class'=>'form-horizontal form-label-left'])!!}
to
{!! Form::open(['method'=>'GET', 'route'=> ['cart-add', $product->id],'class'=>'form-horizontal form-label-left'])!!}
I have a form where I put de id's of my bands table inside a select option. When I select an id in the dropdownlist and try to submit the form, the value always remains NULL. How can I retrieve the value I selected?
create.blade.php file :
<form>
<select name="band_id">
#foreach ($bands as $band)
<option value="{{ $band->band_id }}">{{ $band->band_id }}</option>
#endforeach
</select>
<input type="submit" value="Submit">
</form>
My Bandcontroller inside my store action :
$bands->band_id = $input['band_id'];
First of all you are using #foreach ($band as $band), make sure it's not a typo and if not then fix it (Could be $bands as $band and assumed you know what I mean). Anyways, you may also try this:
{{ Form::select('band_id', $bands, Input::old('band_id')) }}
Just pass the $bands variable to the View and Laravel will create the SELECT for you, you don't need to loop manually. To retrieve the value, you may try this:
$band_id = Input::get('band_id');
Laravel 6 or above
//blade
{!!Form::open(['action'=>'CategoryController#storecat', 'method'=>'POST']) !!}
<div class="form-group">
<select name="cat" id="cat" class="form-control input-lg">
<option value="">Select App</option>
#foreach ($cats as $cat)
<option value={{$cat->id}}>{{ $cat->title }}</option>
#endforeach
</select>
</div>
<div class="from-group">
{{Form::label('name','Category name:')}}
{{Form::text('name','',['class'=>'form-control', 'placeholder'=>'Category name'])}}
</div>
<br>
{!!Form::submit('Submit', ['class'=>'btn btn-primary'])!!}
{!!Form::close()!!}
// controller
public function storecat(Request $request){
Log::channel('stack')->info('name'.$request->app);
if($request->input('cat')==null){ // retriving option value by the name attribute of select tag
return redirect(route('cats.cat'))->with('error', 'Select an app');
}
$this->validate($request,[
'name'=>'required',
]);
}