Laravel search-filter - laravel

I have a problem with passing the selected index to my controller via click.
If I manually change the index in the browser, it is working.
(http://localhost:3000/admin/users?user=&sortBy=5)
$sortOptions is the name of my 2d array in my controller.
sortDisplay is a field in my 2d array in my controller.
Am I missing something in my foreach loop?
<label for="sortBy">Sort by</label>
<select class="form-control" name="sortBy" id="sortBy">
#foreach($sortOptions as $index => $sortOptions)
<option value="{{$index}}" {{ (request()->sortBy == $index ? 'selected' : '') }}>
{{$sortOptions["sortDisplay"]}}
</option>
#endforeach
</select>

Use jQuery to submit form when value changed
So your page will refresh and you will get what you want

In the foreach loop, you are assigning the same variable name as the variable you are iterating. In your case, after the first loop, you re-instantiate the $sortOptions variable with the content of the first index of $sortOptions.
#foreach($sortOptions as $index => $sortOption) // <-- $sortOption, not $sortOption(s)
<option value="{{$index}}" {{ (request()->sortBy == $index ? 'selected' : '') }}>
{{ $sortOption["sortDisplay"] }}
</option>
#endforeach

Related

If old value then select old value of Select Box otherwise select value coming from Controller

I have a select box in the edit form, and everything is working fine, but the problem is when there is an old value, it always selects the value from the database. I think the issue is loop indexing. When I choose an option down from the original value, it selects the old value, but it retains the initial value when selecting an option above the selected value.
<select class="form-control
searchableSelect {{ $errors -> has('Cash_expense_Account') ? 'is-invalid' : '' }}"
name="Cash_expense_Account">
<option value="">Search...</option>
#for($i = 0; $i < count($Cash_Accounts); $i++)
<option value="{{ $Cash_Accounts[$i]['id'] }}"
{{ ( $Cash_Accounts[$i]['id'] == $expense->coa_sub_account_id) ? 'selected' : '' }}
{{ old('Cash_expense_Account') == $Cash_Accounts[$i]['id'] ? 'selected' : '' }}>
{{ $Cash_Accounts[$i]['acc_sub_name'] }}
</option>
#endfor
</select>
Limit the comparison to only use old value if it exists, like:
<option value="{{ $Cash_Accounts[$i]['id'] }}" {{ ( (old('Cash_expense_Account')??$Cash_Accounts[$i]['id']) == $expense->coa_sub_account_id) ? 'selected' : '' }}>
{{ $Cash_Accounts[$i]['acc_sub_name'] }}
</option>
the ?? operator checks if old value exists otherwise use one from the loop.

How to avoid checking every time, if variable is set in blade template? Laravel 8

I know about something like this:
{{ old('contents', $page->contents ?? null) }}
But what about more complicated cases, like checkboxes and selects?
<select id="custom_template" name="custom_template">
{{--default empty option, if nothing is selected yet--}}
<option label=" " {{ ($page->custom_template == null)? "selected" : "" }}></option>
#foreach($templates as $template)
<option value="{{ $template->id }}" {{ ($page->custom_template == $template->id)? "selected" : "" }}>{{ $template->name }}</option>
#endforeach
</select>
I need to avoid checking #isset($page) and also check old input. How can I do it in that select input?
You can use Type hinting to avoid the 'isset'.
Your controller
/**
* Show the form for creating a new resource.
*
* #param \App\Entities\Page $page
*
* #return \Illuminate\View\View
*/
public function create(\App\Entities\Page $page)
{
return view('page', compact('page'));
}
With using 'Type hinting' in create function will create empty collection of Page Entities. No need to check isset condition in view, $page->custom_template will give you null now, instead of error.
And your view, to check the old input.
<select id="custom_template" name="custom_template">
<option value="">Select Option</option>
#foreach($templates as $template)
<option value="{{ $template->id }}" {{ (old('custom_template', $page->custom_template) == $template->id) ? 'selected' : '' }}>{{ $template->name }}</option>
#endforeach
</select>
By using the above condition you can use same view for create and edit function.
Hope, this will solve your problem.
I'm not sure I quite understand what you're trying to do but this approach may help; provided you're using JQuery:
<script>
$(document).ready(function() {
#if($page->custom_template)
$('option[value="{{ $page->custom_template}}"]').prop("selected", true);
#endif
});
</script>

Setting the initial position in select does not work

I want to display it in a loop for #foreach and display the corresponding one at the beginning
<label for="user_name">employee</label>
<select name="user_name">
<option value="{!!null!!}" #if($param['user_name'] == '') selected #endif>no</option>
#foreach($users as $user)
<option value="{{$user->name}}" #if($param['user_name'] == '{{$user->name}}') selected #endif>{{$user->name}}</option>
#endforeach
</select>
However, this is not a good choice
Is there no good way
There is no need to use {{}} or echo the variable inside of #if directive like we donot compare the value in simple PHP by echo the variable.
So #if can be written simply as :
#if($param['user_name'] == $user->name)
and you need to re-write second option like inside the foreach like:
<option value="{{$user->name}}" #if($param['user_name'] == $user->name) selected #endif>{{$user->name}}</option>
Hope it works for you now.

Laravel 5 - Pre-populate a HTML select using database value and old

I am trying to use 'old' in a Laravel 5 app to pre-populate a select form on an edit route like this...
<select id="category" name="category" required>
<option value="">Select</option>
<option value="animal" #if (old('category') == "animal") {{ 'selected' }} #endif>Animal</option>
<option value="vegetable" #if (old('category') == "vegetable") {{ 'selected' }} #endif>Vegetable</option>
<option value="mineral" #if (old('category') == "mineral") {{ 'selected' }} #endif>Mineral</option>
</select>
This works well and keeps the selected option if a validation fails, but I am trying to make it work so that it pre-populates when the page first loads.
How do I determine if this is the first load of the edit page, or if it has reloaded after a validation failure? Or is there a better way to do this?
Lets imagine you have sent the category value as $category.
So in every <option> tag,
<option value="animal"
{{ old('category') == 'animal' ? ' selected' :
$category == 'anumal' ? ' selected' : '' }}>
Animal
</option>
This is what is going on there:
if there is an old value and its matching, select this,
else if the original value is matching select this,
else do nothing.
Use the second parameter of the old function with a default/initial value:
<option value="animal" #if (old('category', 'animal') == "animal") {{ 'selected' }} #endif>Animal</option>
The second parameter will be returned as the function result if an old value cannot be found in the flashed input.

How to show selected value from database in dropdown using Laravel?

I want to show selected value from database into dropdown list on page load.
My controller index function is :
public function index()
{
$country_data =DB::table('country')->select('country_id','country_name')->get();
$profile_data= DB::table('profiles')->select('*')->where('id',$user_id)->first();
return view('profile_update',compact('profile_data','country_data'));
}
Column name in database for height is :Height
My dropdown in profile_update.blade.php is
<select class="select4" name="country" id="country">
<option value="">Please Select</option>
#foreach($country_data as $country)
<option value="{{$country->country_id}}" {{$country_data->country == $country->country_id ? 'selected' : ''}}>{{$country->country_name}}</option>
#endforeach</select>
This is a example of how I do this:
<select class="js-states browser-default select2" name="shopping_id" required id="shopping_id">
<option value="option_select" disabled selected>Shoppings</option>
#foreach($shoppings as $shopping)
<option value="{{ $shopping->id }}" {{$company->shopping_id == $shopping->id ? 'selected' : ''}}>{{ $shopping->fantasyname}}</option>
#endforeach
</select>
In order to understand it fully you will need basics of laravel (MVC),
Let suppose, you have controller. In my case I made a separate table for drop down values.
My Approach --- Separate table for values of drop down, you can try different approach but my explanation was mainly focused on concept.
Note: PersonInfo is model, sampleType is model of my drop down values and don't forget to make a route for the controller.
ExampleController{
public funtion getValues($id){
/*
I am fetching information of a single row from the database by id and
then passing it to the view. The $id to the function came from the
request by your view/form.
I also fetched the values of drop down from the separate table
of database and passed it to the exampleView.
*/
$selectedValue=PersonInfo::findOrFail($id);
$sampleType=SampletypePicker::all(); //model for fetching all values of drop down
return view('exampleView',compact('selectedValue','sampleType));
}
}
So, in the above controller I fetched all values and passed it to the ExampleView. Now in your View file you have to work likewise.
exampleView.blade.php add the below code
<?php $options=$selectedValue->sample_type ?> //note take the value from the database which stored for the individual record and match it with the selected one.
<select class="form-control" name="test">
<option>Select Test Type</option>
#foreach ($sampleType as $value)
<option value="{{ $value->sample_type }}" {{ ( $value->sample_type == $options) ? 'selected' : '' }}>
{{ $value->sample_type }}
</option>
#endforeach
</select>
It is one of the best approach when you want to add dynamic values to the drop down. I mean if you want to add more values to the select tag options then this is the best approach.
Another Approach - take the idea
<?php $months = array("Jan", "Feb", "Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"); ?>
<?php $options=$patient_data->month ?>
#if($patient_data->month)
<select id="expiry_month" name="month" class="form-control-sm">
#foreach($months as $month)
<option value="{{$month}}" {{($month==$options)? 'selected':'' }}>{{$month}}</option>
#endforeach
</select>
#endif
<span class="select-icon"><i class="zmdi zmdi-chevron-down"></i></span>
</div>
OUTPUT of ABOVE CODE
#Sarita Sharma show the error(s). Maybe then anyone help you to resolve this problem. Show data in colections in controler - use dd e.g.
dd($country_data);
dd($profile_data);
Do you want to display the country in the view with the appropriate Height value from profile_data?
Ps. How to put the code, please use the formatting code - put the code in `` and use camelCase in value name (maintaining good PSR-1 practice) - it is easier to read code.
Well, simply if anyone still looking for this, here is the simple way to select items for dropdown from database to blade view
$users = Users::pluck('name', 'id');
$selectedID = 2;
return view('users.edit', compact('id', 'users'));
add this in the controller function before rendering the view
and in the blade view, simply use this variable as foreach loop as
<select name="user_id" class="form-control" id="exampleFormControlSelect1">
#foreach ($users as $key => $value)
<option value="{{ $key }}" {{ ($key == $selectedID) ? 'selected' : '' }}>
{{ $value }}
</option>
#endforeach
</select>
if you don't want to select all users from DB, you can use where condition before pluck condition as
$users = Users::where('status', 1)->pluck('name', 'id');
works with Laravel 8 and Laravel6

Resources