PHP Laravel Getting Unique / Distinct String From Database - php

Basically I am creating a filter button to return query based on the string that was saved on the database. Here is my code:
<div class="input-group mb-3">
<select class="custom-select" id="inputGroupSelect">
<option selected>Filter By Name</option>
#foreach ($events as $event )
<option value="{{ $event->event_parts }}">{{ $event->event_parts }}</option>
#endforeach
</select>
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="button">Filter</button>
</div>
</div>
Since they are strings, how do I create a distinct select option field retrieving only unique strings from the database?
I tried using distinct() and unique() but both returned with errors.

change $events to $events->unique('event_parts'), which would filter out al non-unique $events based on the event_parts parameter (assuming it is a parameter, otherwise you'd use ->filter() and with a callback function).

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

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>

Populate multi select with selected values in laravel 5.2

I have stored multiselect values in database as string
Now while trying to edit the values in need to fetch this highlighted string as array and send it to edit view , so that i can populate multi select with this selected values.
My code in view for multi select
<div class="form-group">
<label class="control-label col-md-3">News For
<span class="required" aria-required="true"> * </span>
</label>
<div class="col-md-4">
{!! Form::select('news_todisplay[]',['users'=>'Users','staff'=>'Staff','cinemahall'=>'Cinemahall'],$todisplayarray,array('class'=>'form-control','multiple'=>'multiple')) !!}
</select>
</div>
</div>
Where $todisplayarray is the array fetched from database i.e they are users,staff, cinemahall
My controller code
public function edit($id)
{
$newsdetails=General_news::findOrFail($id);
$todisplayarray=explode(',',$newsdetails->news_todisplay);
return view('admin.editnews',compact('newsdetails','todisplayarray'));
}
Page view-source shows this
<select class="form-control" multiple="multiple" name="news_todisplay[]"><option value="users">Users</option><option value="staff">Staff</option><option value="cinemahall" selected="selected">Cinemahall</option></select>
This only shows last value as selected, where as it should display 3 of the values as selected.
Kindly let me know where I am going wrong.
Find the below answer
<?php
//get the old values from form
$old = old('category');
//get data from database table field
$cate= explode(',',$data->category_ids);
//stay the values after form submission
if($old){ $cate=$old; }
?>
<select id="categories" name="category[]" multiple>
#foreach ($categories as $val)
<option value="{{ $val->id }}" <?php echo in_array($val->id,$cate)?"selected" :"" ;?> >{{ ucfirst($val->category_name) }}</option>
#endforeach
</select>
I've used loop the categories data with id's and match the data stored in the table

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