Laravel ErrorException, Performing Multiple dynamic drop down - php

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

Related

Laravel 5.4 Undefined variable error - problem with controller?

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)

Fill select box from other vuejs laravel axios

I have two tables, SALARIE and CHANTIER, between them the relationship hasMany BelongsTTO, chantier1 (salarie1, salarie2, salarie3...), in my blade I have two selections, I want when I choose in select 1(chantier) to the the 2nd select(salaries) fill in with salaries of Chantier chosen.
SalarieController
public function pointage()
{
$chantiers = Chantier::all();
return view('pointage', ['chantiers' => $chantiers]);
}
pointage.blade.php
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.16/dist/vue.js"></script>
<div id="app">
<div class="form-group ">
<label>chantier:</label>
<select class="form-control" #change="onChange">
#foreach($chantiers as $chantier)
<option value="{{ $chantier->id }}">{{ $chantier->nomC }} {{ $chantier->id }}</option>
#endforeach
</select>
</div>
<div class="form-group ">
<label>salarie:</label>
<select class="form-control" #change="onChange">
#foreach($salaries as $salarie)
<option value="{{ $salarie->id }}">{{ $salarie->nomS }} </option>
#endforeach
</select>
</div>
</div>
vuejs code
const app = new Vue({
el: "#app",
data: function() {
return {
message: "Vue"
}
},
methods: {
onChange(event) {
}
}
})
Route
Route::get('pointage', 'SalarieController#pointage');
You can define computed variable salaries and on chantiers changes make request and if done fill salaries with response data and instead of using laravel's for each use v-for="salary in salaries.
Hope it help u.

How to use a variable as "value" attribute in <option> tag

I'm currently using Laravel and I want to have a dropdown box display category names from my database, but when selected the value it returns to the server should be a numerical value of the name selected which is also stored in the database.
Like so:
#foreach($categories as $category)
<option name="pid" value="$category->id" id="cname">{{$category->name}}</option>
#endforeach
The values are passed from my Controller to the Blade template. As you can see, I want it to display the category names in the drop down (which it does fine), but once selected and submitted, I want the category ID to be returned. Since the "value" attribute returns the value, I want to have the variable $category->id as the "value". I want to do this without using JavaScript or jQuery. Only with PHP. How would I go about accomplishing this and is it even possible?
When I try to use value="{{$category->id}}" I get the Laravel error:
Integrity constraint violation: 1048 Column 'parent_id' cannot be null
So it seems like it isn't submitting the value of the dropdown.
Here is the code I'm currently using in my Blade template:
<form class="" action="{{route('createsubcategorypost')}}" method="post">
<div class="form-group">
<label for="cname">Sub-Category name:</label>
<input type="text" name="cname" value="" placeholder="Sub-Category Name" id="cname" class="form-control">
</div>
<div class="form-group">
<label for="pid">Parent ID</label>
<select class="form-control">
#foreach($categories as $category)
<option name="pid" value="{{$category->id}}" id="pid">{{$category->name}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<center>
<button type="submit" name="button" class="btn btn-success">Create Sub-Category</button>
</center>
</div>
{{csrf_field()}}
</form>
And this is the code in my Controller:
public function CreateSubCategoryPost(Request $request){
if ($request->cname == null) {
session()->flash('errormessage',' Invalid sub-category name.');
return redirect()->back();
}
$scc = SubCategory::where('name',$request->cname)->first();
if ($scc !== null) {
session()->flash('errormessage',' Sub-category with that name already exists.');
return redirect()->back();
}
$subCategory = new SubCategory;
$subCategory->name = $request->cname;
$subCategory->uniqueid = 'SCA'.str_random(28);
$subCategory->slug = str_slug($request->cname,'-');
$subCategory->parent_id = $request->pid;
$subCategory->save();
return redirect()->route('categories');
}
Same way you you are displaying the category name inside the option tag :
#foreach($categories as $category)
<option name="pid" value="{{$category->id}}" id="cname">{{$category->name}}</option>
#endforeach
Everything you call from a database in Laravel should have the format {{$category->someName}} no matter where you place it in your view. In your case you need to enclose $category->id in {{ }}

Laravel 5.1 - Store input data in my session

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'])!!}

Laravel : Form select option value is always NULL when submitting

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

Categories