How to show old data of select element - laravel

I am stuck for 2 days, do you know how to show old data of select element in Laravel?
<select name="sexe" id="sexe" class="form-control">
<option value="">Choice</option>
<option>Women</option>
<option>Man</option>
</select>
I have tried this but without success:
<select class="form-control" name="sexe">
<option value="male" #if (old('sexe') == 'male') selected="selected" #endif>male</option>
<option value="female" #if (old('sexe') == 'female') selected="selected" #endif>female</option>
</select>
My Controller
public function edit($id)
{
//
$candidats = Candidat::find($id);
$permis = Permis::all();
return view('admin.candidats.edit', compact('candidats', 'permis'));
}
public function update(Request $request, $id)
{
$request->validate([
'sexe' => 'required|string',
'fk_permis' => 'required'
]);
$candidats = Candidat::find($id);
$candidats->sexe = $request->get('sexe');
$candidats->fk_permis = $request->get('fk_permis');
$candidats->save();
return redirect()->route('candidats.index')
->with('success', 'mise à jour effectuée');
}
Edit:
1) index.blade.php
2) edit.blade.php

In your update function put withInput():
return redirect()->route('candidats.index')
->with('success', 'mise à jour effectuée')->withInput();
In your select you can do this:
<select class="form-control" name="sexe">
<option value="male" #if (old('sexe') == 'male') selected="selected" #elseif($candidats->sexe == 'male') selected="selected"
#endif>male</option>
<option value="female" #if (old('sexe') == 'female') selected="selected" #elseif($candidats->sexe == 'female') selected="selected"
#endif>female</option>
</select>
I loaded the selected option from your model here
#elseif($candidats->sexe == 'male') selected="selected"
So, if you saved 'male' in your sexe attribute this option will be selected.
Take a look here for more info:

If the old data was stored as a model, which I assume it was since this is a Laravel question and not a javascript question, you can use form-model binding to easily load the old data the next time you go to the page.
So, when you open your form, bind the model:
{{ Form::model($yourModel, array('route' => array('yourModel.update', $yourModel->id))) }}
And then within the select method, laravel (collective) can automatically make the old data the selected value. Using the Laravel helper it might look like this:
{!! Form::select('sexe', $listOfYourNameAndIdForYourSelectItem, null, ['class'=>'form-control', 'id'=>'sexe']) !!}
By making the third argument null, as above, Laravel will make the model's old data the selected element.
Check the docs on the Laravel forms package for more info.

Related

Redering out a view based on dropdown value in Laravel 7

I would like to render a different view for 4 dropdown values in the controller. I'm new to PHP and Laravel and just starting to understand it.
dropdown html:
<div class="col-md-6">
<select name="employees" class="form-control #error('employees') is-invalid #enderror">
<option value="">-- {{ __('choose') }} --</option>
<option value="micro">1 - 5</option>
<option value="small">5 - 50</option>
<option value="medium">50 - 500</option>
<option value="large">500 +</option>
</select>
Controller:
class RegisterControllerStep2 extends Controller
{
public function form()
{
return view('auth.register_step2');
}
public function saveData(Request $request)
{
auth()->user()->update($request->only(['company_name', 'website', 'employees']));
return redirect()->route('home');
}
}
I want to redirect the user to another page other than home based on their selection from the employees dropdown above.
You need something like this
public function saveData(Request $request)
{
auth()->user()->update($request->only(['company_name', 'website', 'employees']));
if($request->employees==='micro'){
return redirect()->route('micro');
}
return redirect()->route('home');
}
Another thought I had on this is you could also do something like
return redirect()->route($request->employees);
As long as you had all your routes set up correctly with matching names to the values in your employees select
For giving a better experience I add this jquery function to justrusty's answer.
By doing this, it is not required for the user to press submit button for changes being applied.
Add a form with an id on the select:
<form action="something" method="post">
#csrf
<select id="employees" name="employees" class="form-control #error('employees') is-invalid #enderror">
<option value="">-- {{ __('choose') }} --</option>
<option value="micro">1 - 5</option>
<option value="small">5 - 50</option>
<option value="medium">50 - 500</option>
<option value="large">500 +</option>
</select>
</form>
Then add below jquery to the end of body section:
$('#employees').change(function() {
this.form.submit();
});
And at last, as justrusty said, redirect to the desired page in the controller:
if($request->employees==='micro'){
return redirect()->route('micro');
}

Eloquent Value of html select option not getting to controller to sort page

My controller doesn't seem to receive the value of the selected option i always get return of ''. I am trying to use this value to sort the view.
View:
<select class="form-control" name="sorteren" id="sorteren">
<option value="Name,asc">Name (A => Z)</option>
<option value="Name,Desc">Name (Z => A)</option>
<option value="Email,Asc">Email (A => Z)</option>
<option value="Email,Desc">Email (Z => A)</option>
</select>
Controller
$selectvalue = $request->input('sorteren');
$selectvalue = explode(',', $selectvalue);
$users = User::orderBy($selectvalue[0],$selectvalue[1])
Error i am getting:
"Undefined offset: 1"

How to retrieve selected option value?

Hi guys new to laravel here! i am using selected option drop down list The First Select contains the countries and the second one has the states, now When i try to store the in database i am not getting the proper selected state instead i am always getting the first state in the second select Option!! i am using query Builder.
This is How i am retrieving Countries and states
public function store(Request $request)
{
$country = DB::table("countries")->where("id",$request->daira);
$state = DB::table("states")->where("country_id",$request->daira);
$daira = $country->get()->first()->name;
$impact = $state->get()->first()->commune;
dd($impact);
}
Note: dd($impact); Should be retrieving the selected state, instead it's retrieving the first value on the Selection List
So my Question is How do i get it to retrieve The proper Selected state !? Hope my question is clear Thanks in Advance.
Updated:
In the First Select option I have Countries name and in the second option i have
states each country has maximum 3 states, let's say Country A has 3 States A1,A2 and A3 And i want to select State A2 from the select option Value and instead of getting A1 by default like my case in the Question
Updated: I Am using VueJs
This is The form code
<template>
<div class="modal-body">
<div class="form-group">
<select name="direction" class="form-control">
<option value="">Selctionner Direction</option>
<option value="ENERGIE">ENERGIE</option>
<option value="HYDRAULIQUE">HYDRAULIQUE</option>
<option value="ENVIRONNEMENT"> ENVIRONNEMENT</option>
<option value="AMENAGEMENT">AMENAGEMENT</option>
<option value="P.T.T">P.T.T</option>
<option value="TOURISME">TOURISME</option>
<option value="TRANSPORT">TRANSPORT</option>
<option value="TRAVAUX PUBLICS">TRAVAUX PUBLICS</option>
<option value="EDUCATION">EDUCATION</option>
<option value="ENSEIGNEMENT SUPERIEUR">ENSEIGNEMENT SUPERIEUR</option>
<option value="URBANISME">URBANISME</option>
<option value="FORMATION PROFESSIONNELLE">FORMATION PROFESSIONNELLE</option>
<option value="SANTE">SANTE</option>
<option value="JEUNESSE-SPORTS CULTURE">JEUNESSE-SPORTS CULTURE</option>
<option value="PROTECTION SOCIALE">PROTECTION SOCIALE</option>
<option value="INFRASTRUCTURES ADMINISTRATIVES">INFRASTRUCTURES ADMINISTRATIVES</option>
<option value="HABITAT">HABITAT</option>
<option value="COMMERCE">COMMERCE</option>
<option value="LOGEMENT">LOGEMENT</option>
<option value="LOCAUX A USAGE PROFESSIONNELE">LOCAUX A USAGE PROFESSIONNELE</option>
<option value="FORET">FORET</option>
</select>
</div>
<div class="form-group">
<label>Selctionner Daira:</label>
<select name="daira" class='form-control' v-model='country' #change='getStates()'>
<option value='0' >Select Country</option>
<option v-for='data in countries' :value='data.id'>{{ data.name }}</option>
</select>
</div>
<div class="form-group">
<label>Selctionner Commune:</label>
<select name="impact" class='form-control' v-model='state'>
<option value='0' >Select State</option>
<option v-for='data in states' :value='data.id'>{{ data.commune }}</option>
</select>
</div>
<div class="form-group">
<label >Intitule :</label>
<input type="text" class="form-control" name="intitule" required>
</div>
</div>
</template>
And this is My Script
<script>
export default {
mounted() {
console.log('Component mounted.')
},
data(){
return {
country: 0,
countries: [],
state: 0,
states: []
}
},
methods:{
getCountries: function(){
axios.get('/api/getCountries')
.then(function (response) {
this.countries = response.data;
}.bind(this));
},
getStates: function() {
axios.get('/api/getStates',{
params: {
country_id: this.country
}
}).then(function(response){
this.states = response.data;
}.bind(this));
}
},
created: function(){
this.getCountries()
}
}
</script>
can you post the result of dd($request->all()) ?
assuming your select name is daira and impact, you should be able to get the posted value with this:
public function store(Request $request)
{
$daira = $request->daira;
$impact = $request->impact;
}
I understand your issue first state returns because of when you passed country id it returns all the state related this country.
So that you need to pass state Id from state drop-down.
<select name="impact">
<option value="id">{{ STATE NAME }} </option>
</select>
And then you need to pass that state id in controller.
$state = DB::table("states")->where("id",$request->impact);
Hope you understand your queries
I assume $request->daira is country ID
public function store(Request $request)
{
//here you selected a country with provided country ID
//this returns Query Builder object
$country = DB::table("countries")->where("id",$request->daira);
//here you are returning all the states where the country_id is
//the provided country ID
//Note that this returns all the states (Query Builder object)
$state = DB::table("states")->where("country_id",$request->daira);
//You return `Illuminate\Support\Collection` then you got the first item
//from collection
$daira = $country->get()->first()->name;
//You returned all the states `Illuminate\Support\Collection`
//and you picked the first state from the collection,
//which is likely the first item in your
//form select field options
$impact = $state->get()->first()->commune;
dd($impact);
}
Because you didn't specify state_id, you will always get lists of all the states under the given country.
I assume table relationship is Country -> hasMany -> State
You need to add state_id as constraint, so only one state is picked
$state_id = $request->state
I assume you have state in your form
$state = DB::table("states")
->where("country_id",$request->daira)
->where('id', $state_id)
->first();
$impact = $state->commune

How to manage in edit items already selected

I have a select2, which lists all items of a database table. One of these items is already selected. In edit mode, how can I show the already selected item and list the rest of the items?
IN CONTROLLER:
$offertaheader = Offertaheader::find($id_offertaheader);
$clients = Client::all()->where('visibility',1)
->sortBy('nome');
return view('offertas.edit',compact('offertaheader','clients'));
IN VIEW BLADE:
<select class="form-control select2" name="id_cliente" style="width: 100%">
<optgroup label="<?php echo htmlentities(utf8_encode('CLIENTE'), 0, "UTF-8"); ?>">
<option></option>
#foreach($clients as $client)
<option value="{{$client->id}}" {{ (old('id_client', $client->id) == ($client ? $client->id : '') ? ' selected' : '') }}>{{$client->nome}}</option>
#endforeach
</select>
I want that the already selected item must be shown and at the same time the user can change it in the blade. I prefer to avoid front-end codings like jquery or ajax.
You can update using sync method, sth like this,
public function upate()
{
$todo = Todo::findOrFail($id);
$data = $request->all();
$todo->update($data);
$users = $request->users;
$users = User::find($users);
$todo->users()->sync($users);
return response()->json("success",200);
}

Get data Based On Selected Value in Drop Down menu - Laravel 5.4

I have two tables posts and category.
My controller:
public function index()
{
$posts = Post::orderBy('id', 'desc')->get(['category']);
$data = DB::table('posts')->paginate(5);
$category = DB::table('category')->pluck('cname','id');
return view('posts.index', [
'posts' => $posts,
'category'=> $category,
'posts' => $data
]);
}
My blade:
<select class="form-control" name="category" id="category_add">
<option value="">Select Category</option>
#foreach($category as $key=>$value)
<option value="{{ $key }}">{{ $value }}</option>
#endforeach
</select>
Now my code shows a drop down data from the database...
What I need is: When I select the drop down category it should only shows the particular category of data in the view dynamically
Any one help
Did you mean after selecting a category from the dropdown there will be another section which will show data about that specific category?
One way to do it is through ajax request. I dont know if i got your question right or wrong. can u explain a bit if i got it wrong?

Resources