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'])!!}
Related
I am trying to create a search with multiple filters, one of the filters is a budget or price filter and I am using dropdown instead of creating a price range bar.
In other words, my budget filters are:-
0-2500000
250000-500000
500000-10000000
10000000-25000000
25000000-50000000
50000000 and above
Here is my code and I need help modifying it. The function in Controller and SQL Query in the model only takes a single budget (price) value and displays the result, instead of taking the budget (price) range and showing the result which comes under that budget (price) range.
What I want to achieve is that when the user selects the budget (price) range in the search form, it should display properties that fall under the selected budget range or price range.
HTML Form
<div class="search__area-inner">
<?= form_open('/home/search_residential'); ?>
<div class="row">
<div class="col-12"><?= csrf_field(); ?></div>
<div class="col-6 col-lg-4 col-md-4">
<div class="form-group">
<select name="budget[]" class="wide select_option">
<option data-display="Select Budget">Select Budget</option>
<option value="0-2500000">less than 25 lacs</option>
<option value="250000-500000">25 to 50 lacs</option>
<option value="500000-10000000">50 lacs to 1 cr</option>
<option value="10000000-25000000">1 cr to 2.5 cr</option>
<option value="25000000-50000000">2.5 cr to 5 cr</option>
<option value="50000000">5 cr +</option>
</select>
</div>
</div>
<div class="col-6 col-lg-4 col-md-4">
<div class="form-group">
<select name="type" class="wide select_option">
<option data-display="Select Property Type">Select Property Type</option>
<option value="Apartments">Apartments</option>
<option value="Bungalow">Bungalow</option>
<option value="Row House">Row House</option>
<option value="Villas">Villas</option>
</select>
</div>
</div>
<div class="col-6 col-lg-4 col-md-4">
<div class="form-group">
<input type="text" class="form-control" id="inputLocation" name="city" value="" placeholder="Enter City" required>
</div>
</div>
<br>
<div class="mx-auto">
<div class="form-group">
<button class="btn btn-primary text-uppercase btn-block"> search
<i class="fa fa-search ml-1"></i>
</button>
</div>
</div>
</div>
<?= form_close(); ?>
</div>
Controller code
public function search_residential() {
$data['getfooter'] = $this->homeModel->getFooterInfo();
$data['getad'] = $this->homeModel->getCarousel();
$data['pagelist'] = $this->pageModel->getPages();
$data['cities'] = $this->db->table('tblcity')->select('*')->get()->getResult();
$params = array(
'budget' => $this->request->getVar('budget'),
'type' => $this->request->getVar('type'),
'city' => $this->request->getVar('city'),
);
$data['search'] = $this->homeModel->getSearch($params);
return view('searchresidential', $data);
}
**Model code**
//Searching residential data
public function getSearch($params) {
$budget = $params['budget'];
$type = $params['type'];
$city = $params['city'];
$builder= $this->db->table('tblresidential');
$builder->select('*');
$builder->where('1 = 1');
if ($budget != '') {
$builder->where('budget', $budget);
}
if ($type != '') {
$builder->where('type', $type);
}
if ($city != '') {
$builder->where('city', $city);
}
return $builder->get()->getResult();
}
Instead of:❌
// ...
$builder->where('budget', $budget);
// ...
Use this:✅
// ...
foreach ($budget as $range) {
$builder->orWhere((function (string $range) {
$limits = array_map(
fn($limit) => floatval($limit),
explode("-", $range)
);
return match (count($limits)) {
1 => ['budget >=' => $limits[0]],
2 => ['budget >=' => $limits[0], 'budget <=' => $limits[1]],
default => ['1 =' => 1]
};
})($range));
}
// ...
Resource: $builder->where() : Associative array method
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'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"}'>
I have four tables:
asset_category table(columns 'asset_category_id', 'category'), an assets table(columns 'asset_id','asset_category_id','manufacturer_id', 'department_id'),
manufacturers table (columns manufacturers_id, manufacturer) and departments table (columns department_id, department). The asset table columns are linked with the other three table. I'm performing a dynamic drop down in the form to insert into the asset table
Asset.blade.php
<form action="{{url('/insertAsset')}}" method="POST" edata-parsley-validate novalidate>
{{ csrf_field() }}
<div class="form-group">
<label for="userName">Asset ID*</label>
<input type="text" name="asset_id" parsley-trigger="change" required placeholder="Asset ID" class="form-control" id="userName" disabled>
</div>
<div class="form-group">
<label for="userName">Asset Category ID*</label>
<select name="asset_category_id" parsley-trigger="change" required placeholder="Asset Category ID" class="form-control">
<option>Select an Asset Category</option>
#foreach( $asset_categories as $asset_category )
<option value=" {{$asset_category->asset_category_id}}"> {{ $asset_category->category }} </option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="userName">Asset Manufacture ID*</label>
<select name="manufacturer_id" parsley-trigger="change" required class="form-control">
<option>Select a Manufacturer</option>
#foreach( $manufacturers as $manufacturer )
<option value=" {{$manufacturer->manufacturer_id}}"> {{ $manufacturer->manufacturer }} </option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="userName">Department ID*</label>
<select name="department_id" parsley-trigger="change" required placeholder="Department ID" class="form-control" >
<option>Select a Department</option>
#foreach( $departments as $department )
<option value=" {{$department->department_id}}"> {{ $department->department }} </option>
#endforeach
</select>
</div>
<div class="form-group text-right m-b-0">
<button class="btn btn-primary waves-effect waves-light" type="submit">
Submit
</button>
</div>
AssetController
<?php
namespace App\Http\Controllers;
use App\Asset;
use App\Asset_category;
use App\Manufacturer;
use App\Department;
use Illuminate\Http\Request;
class AssetController extends Controller
{
public function asset_category(){
$asset_categories = Asset_category::all();
return view('asset', ['asset_categories' => $asset_categories]);
}
public function manufacturer(){
$manufacturers = Manufacturer::all();
return view('asset', ['manufacturers' => $manufacturers]);
}
public function department(){
$departments = Department::all();
return view('asset', ['departments' => $departments]);
}
}
Web.php
<?php
Route::get('/asset', function (){
return view('asset');
} );
Route::get('/asset', 'AssetController#asset_category');
Route::get('/asset', 'AssetController#department');
Route::get('/asset', 'AssetController#manufacturer');
/*POST */
Route::post('/insertAsset', 'AssetController#add');
When run the application, i get an ErrorException which states:
Undefined variable: asset_categories (View: C:\xampp\htdocs\laravel_app\resources\views\asset.blade.php).
After thorough testing i find out that, just one drop down displays because the laravel routes only one variable from one function among the 3 functions in the web.php and the other two variable from the other functions are not sent to the asset.blade.php. So now i want a way to route the other variables to the asset.blade.php. Please help if you understand it. Thanks in advance.
The first thing is that Laravel will only match the first route with the specific ID and specific type. In these case will only find the first route GET /asset.
To do what I undestand you want. You need to create only one method, that will return the three variables to the view
public function asset(){
$asset_categories = Asset_category::all();
$manufacturers = Manufacturer::all();
$departments = Department::all();
return view('asset', ['asset_categories' => $asset_categories,
'manufacturers' => $manufacturers, 'departments' => $departments]);
}
And only one route
Route::get('/asset', 'AssetController#asset');
I have an issue recieving the data from a form which was modified with AJAX.
I have 2 fields: Cinema and Session.
The Session field updates automatically based on which cinema you have chosen. However, when I try to get the session field's value in my controller, it returns as "" (blank) where-as I want it to return what is actually displayed in the drop down box in the form.
Code:
Script:
<script>
$('#cinema').on('change', function(e){
console.log(e)
var cinema_id = e.target.value;
//ajax
$.get('{{ url('/ajax-subcat') }}?cinema_id=' + cinema_id, function(data){
//success data
console.log(data)
$('#sesh').empty();
$.each(data, function(index, subcatObj){
$('#sesh').append('<option value="'+subcatObj.id+'">'+subcatObj.session_time+'</option>');;
});
});
});
</script>
Controller:
public function cart()
{
$formData = array(
'cinema' => Input::get('cinema'),
'sesh' => Input::get('sesh'),
'ticketType' => Input::get('ticketType'),
'count' => Input::get('count')
);
$cinemaDetails = Cinema::find($formData['cinema']);
$session = Session::find($formData['sesh']);
return view('movies/ticketpage/cart')
->with('formData', $formData)
->with('cinemaDetails', $cinemaDetails)
->with('session', $session);
}
View/Blade file:
<div class="container">
<div class="row">
<div class="col-sm-4">
<h2>{{$movie->title}}</h2>
<img src="/WDAAssign2/Assign2-A/{{ $movie->image }}" height="200" width="150">
<p>{{ $movie->description }}</p>
</div>
<div class="col-sm-4">
<h2>Purchase tickets!</h2>
{!! Form::open(array('action'=>'MoviePageController#cart', 'files'=>true)) !!}
<label>Select a Cinema:</label><br>
<select id = "cinema" name = "cinema">
#foreach ($cinemas as $cinema)
<option value="{{$cinema->id}}">{{$cinema->name}}</option>
#endforeach
</select>
<br>
<label>Select a session:</label>
<br>
<select id = "sesh" name = "sesh">
<option value=""></option>
</select>
<br>
<label>Type of ticket:</label>
<br>
<select id= ="ticketType">
<option value="adult">Adult</option>
<option value="concession">Concession</option>
<option value="children">Children</option>
</select>
<br>
<label>Number of tickets:</label><br>
<select id = "count" name ="count">
#for ($i = 1; $i < 10; $i++)
<option value="{{$i}}">{{$i}}</option>
#endfor
</select>
<br><br>
<input type="submit" value="Submit">
{!!Form::close()!!}
</div>
</div>
</div>
Routes:
Route::post('/movie/ticketpage/cart', 'MoviePageController#cart');