Populating Select Box based on ID - PHP - php

I have two tables, schools and grades and they are many to many related. I have successfully set up the many to many relationships in the model already.
I am able to insert the select box value into the database but i having difficulty try to fetch.
When i click on a grade with id = 1 for instance, i am trying to fetch its corresponding school into the select box including the values. i get an error Integrity constraint violation: 1052 Column 'id' in field list is ambiguous.
What am i not doing right in my query?
controller
public function editPage($id)
{
$grade = Grade::whereId($id)->firstorFail();
$schools = $grade->schools()->pluck('id')->toArray();
return view('grades.edit',compact('grade','schools'));
}
Model
public function schools()
{
return $this->belongsToMany('App\School')
->withTimestamps();
}
View
<div class="form-group">
<label for="select" class="col-lg-2 control-label">School</label>
<div class="col-lg-10">
<select class="form-control" id="school" name="school[]" mulitple>
#foreach($schools as $school)
<option value="{!! $school->id !!}" #if(in_array($school->id, $schools)) selected="selected" #endif >
{!! $schools->name !!}
</option>
#endforeach
</select>
</select>
</div>
</div>

$school is an array in your case, so your view most likely can't decide what to do with $school->id...
Seems more likely you wanna just use school models in your view, so just only compact('grade') and then use foreach($grade->schools as $school) in your view.
Also your conditional for selected options seems wrong, every $school (which is only an id at this point, because $schools is an array of ids) is obviously in $schools because that's how your foreach is set up. But you should fix the other thing first.

I think it's probably because it's not sure what 'id' you want to pluck.
Try
$schools = $grade->schools()->pluck('schools.id')->toArray();
You could also just pass the grade and get the schools in the view...
public function editPage($id)
{
$grade = Grade::whereId($id)->with('schools')->firstorFail();
return view('grades.edit', compact('grade'));
}
And then
$school_options = $grade->schools->pluck('name', 'id');
#foreach($school_options->all() as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
#endforeach

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)

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 {{ }}

How do i send and store values of a dynamically populated select field with Laravel framwork

I'm working with Laravel 5.4 and I have a select field that is dynamically populated from a department's table.
EmployeeController create model
public function create()
{
$departments = Department::orderBy('name', 'ASC')->get();
return view('emp.create', compact('departments'));
}
Select from field dynamically populated
<div class="form-group">
<label for="department" class="col-md-4 control-label">Department</label>
<div class="col-md-6">
<select name="dept_id" id="dept" class="form-control" required autofocus>
<option></option>}
#foreach ($departments as $department)
<option value="{{ $department->id }}">{{ ucfirst($department->name )}}</option>
#endforeach
</select>
</div>
In my employee's table, I have the dept_id column which references the department's id column. Every time I submit the form, 0 is inserted in the employees dept_id column instead of the actual value. When I dd($request) I can see the actual department.id being sent in the request array.
EmployeeController store model
public function store(Request $request)
{
//dd($request);
$employee = Employee::create(request()->all());
}
What's the reason the query inserts 0 everytime?

Select is not gettion the value of the option

I am working in laravel and I am passing a model into a view and I am showing one of the attributes of the model in every option but I need that the value is another one, something like showing the name of a model but I need to save the id but it it getting all the model. the code is:
<div class="form-group">
<div class="col-sm-12">
<label for="select2">Persona</label>
<select name="persona" id="persona" class="select2" required>
#foreach ($personas as $persona)
<option value="{{$persona->persona_id}}">{{$persona-
>getNombreApellidoPersona()}}</option>
#endforeach
</select>
</div>
</div>
the method getNombrePersona() is working because is returning the name and the lastname from the table, but when I return what the request give me, this what it is return in the row persona:
"tipo_usuario" => "{"tipo_usuario_id":2,"cliente":1,"nombre":"admin finca","fecha_insert":"2017-04-20 16:58:24","fecha_update":"2017-04-20 16:58:24","eliminado":0}"
And in the chrome when I check the source code in that part this is what it is shown:
<option value="{"persona_id":1,"nombre":"juan","apellido":"aguirre","correo_electronico":null,"fecha_insert":"2017-04-17 20:42:16","fecha_update":"2017-04-17 20:42:16","eliminado":0}">name last name</option>
It is like if the value that I give is replace by the whole information if the model.
I do not know why this is happening, I know that I can simply take the "persona_id" from the whole model but I want to know if it is possible to take directly from the select.
Change loop part to this:
<option value="{{ $persona->persona_id }}">{!! $persona->getNombreApellidoPersona() !!}</option>
By default, Blade {{ }} statements are automatically sent through PHP's htmlspecialchars function to prevent XSS attacks. If you do not want your data to be escaped, you may use the following syntax:
Hello, {!! $name !!}
https://laravel.com/docs/5.4/blade#displaying-data

Laravel render dropdown list from related table under employee table

I have 2 tables. Employee table and Roles tables. In my employee.show blade I want to render the dropdown list of the role already assgined or available to assign. I am not using collective forms and am a little stuck as all tutorials use thse.
My controller
public function show($employee)
{
$employee = Employees::find($employee);
$roles = Roles::pluck('role_name', 'id');
return view('employees.show')->withEmployee($employee)->withRoles($roles);
}
and my show.blade. Question is how do i pull the complete list from db of all other roles so a user can update?
<div class="form-group">
<label class="col-md-4 control-label" for="roles_id">Role</label>
<div class="col-md-4">
<select id="roles_id" name="roles_id" class="form-control">
<option value="{{ $employee->roles->id }}">{{ $employee->roles->role_name }}</option>
</select>
</div>
</div>
What you've done in your controller seems correct. Your view however should loop through the roles and create options for them. Bear in mind, that you've used Role::pluck('role_name', 'id'), which will return an array of 'id' => 'role_name'.
You can decide which one is selected by adding a selected attribute to the employee's role option by using a ternary statement, which compare's the employee's role_id to the role_id we're currently looking at in the loop.
Try something like this:
<select name="roles_id">
<option value="">Select...</option>
#foreach ($roles as $roleId => $roleName)
<option value="{{ $roleId }}"{!! $employee->role_id == $roleId ? ' selected' : '' !!}>{{ $roleName }}</option>
#endforeach
</select>

Categories