Redering out a view based on dropdown value in Laravel 7 - laravel

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

Related

Insert a Form value from a select in a dynamic url

While using laravel to create a movie catalog, I am trying to extract the value from an HTML Form and insert it in the URL.
The objective is that, from the main page which is:
http://127.0.0.1:8000/index/
I want it to extract an ID value from the form and insert it in the url:
http://127.0.0.1:8000/index/1
http://127.0.0.1:8000/index/2
http://127.0.0.1:8000/index/3
As each one is a dynamic view that will display each movie information from the database.
The form is already recognizing the ids and is displaying them in the select form in page, but I am not able to have that value used to insert it in the url as shown above.
Please help me, here is my code:
index.blade.php
<form action=" WHAT TO PLACE HERE??? " method="POST">
#csrf
<select name="selector">
<option value="" disabled selected> --- ID --- </option>
#foreach($movies as $movie)
<option value="{{ $movie->id }}">{{ $movie->id }}</option>
#endforeach
</select>
<button>Buscar</button>
</form>
web.php
Route::get('/index', 'App\Http\Controllers\MovieController#index');
Route::get('/index/create','App\Http\Controllers\MovieController#create');
Route::post('/index','App\Http\Controllers\MovieController#store');
Route::get('/index/{id}','App\Http\Controllers\MovieController#show');
Route::delete('/index/{id}','App\Http\Controllers\MovieController#destroy');
MovieController.php
class MovieController extends Controller
{
public function index() {
$movies = Movie::all();
return view('movies.index', ['movies' => $movies,]);
}
public function show($id) {
$movie = Movie::findOrFail($id);
return view('movies.show', ['movie' => $movie]);
}
public function create() {
return view('movies.create');
}
public function store(){
$movie = new Movie();
$movie->title = request('title');
$movie->synopsis = request('synopsis');
$movie->year = request('year');
$movie->cover = request('cover');
$movie->save();
return redirect('/')->with('mssg','La película a sido registrada');
}
public function destroy($id) {
$movie = Movie::findOrFail($id);
$movie->delete();
return redirect('/index/');
}
}
Replace you form as:
index.blade.php
<form action="" method="POST" id="form_id">
#csrf
<select name="selector" id="selector">
<option value="" disabled selected> --- ID --- </option>
#foreach($movies as $movie)
<option value="{{ $movie->id }}">{{ $movie->id }}</option>
#endforeach
</select>
<button type="submit">Buscar</button>
</form>
Add script after this :
<script>
$('#selector').change(function(){
var selected_value = $(this).val();
$('#form_id').attr('action', 'http://127.0.0.1:8000/'+selected_value);
});
</script>
This will set your action dynamic as per selection with your select tag

ASP.Net Core MVC SelectList not returning selected value to controller

For some reason all the selectlists are returning 0 to my controller. Below is my code, can someone please help?
View:
<div class="row align-items-start">
<div class="col-12">
<select app-for="customer.JobStage_Id"
asp-items="#(new SelectList(Model.jobStages, "Id", "Description",customer.JobStage_Id))"
class="selectpicker col-offset-1"></select>
</div>
</div>
Populate the list:
public IEnumerable<Lookups> getJobStages()
{
List<Lookups> jobStages = context.Lookups
.Where(s => s.Lookup_Type_Id == 15).ToList();
jobStages.Add(new Lookups { Id = 0, Description = "" });
return jobStages;
}
This is the view source code and everything looks correct so I don't understand why my model in my action has zeros for all selectlists.
<div class="row align-items-start">
<div class="col-12">
<select app-for="customer.JobStatus_Id" class="selectpicker col-offset-1"><option value="40">Dormant</option>
<option value="41">Waiting For POB POA Flex</option>
<option value="42">Sent Flex to Council / Awaiting Invoice</option>
<option value="43">Waiting for EST</option>
<option value="44">Waiting for Flex to be sent to Council</option>
<option value="45">Sent for Data Match</option>
<option value="46">Other</option>
<option selected="selected" value="0"></option>
</select>
</div>
</div>
Below is my full view followed by the full action:
[HttpPost]
public IActionResult UpdateCustomer(Customer customer)
{
if (ModelState.IsValid)
{
if (customer.PK_Id == 0)
{
customerRepository.add(customer);
}
else
{
customerRepository.update(customer);
}
}
return RedirectToAction("Index","Home");
}
You can try following code.
In your action:
public IActionResult ViewAction()
{
ViewData["JobStage_Id"] = new SelectList( context.Lookups.Where(s => s.Lookup_Type_Id == 15).ToList(), "Id", "Description");
return View();
}
In your view:
<select asp-for="customer.JobStage_Id" asp-items="ViewBag.JobStage_Id" class="selectpicker col-offset-1">
</select>
Please notice that your code is <select app-for="customer.JobStatus_Id",it should be asp-for,not app.

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 build conditional list of dropdown options in Laravel Voyager

I have a problem with Laravel Voyager v1.2. I need to filter list of related list of options in select dropdown easily by where condition. So let's say I have Post with relation to Category, but I don't want to list all Categories in select dropdown, but just that active ones.
I tried to force Voyager to take my own method to build an relationship in Post model:
public function category_id() {
return $this->belongsTo('Post::class')->where('active',1);
}
Also tried to define scope in BREAD JSON options for the category field:
{
"relationship": {
"key": "id",
"label": "name",
"scopes": [
"active"
]
}
}
Post Model part:
public function scopeActive($query) {
return $query->where('active', 1);
}
This is how my Post class look like (I don't actualy need to filter active categories, but food categories by it's IDs):
public function soup1() {
return $this->belongsTo('App\Meal')->where('meal_category_id',1);
}
public function soup2() {
return $this->belongsTo('App\Meal')->where('meal_category_id',1);
}
public function mealy() {
return $this->belongsTo('App\Meal')->where('meal_category_id',7);
}
public function scopeSoups($query)
{
return $query->where('meal_category_id', 1);
}
public function scopeMealy($query)
{
return $query->where('meal_category_id', 7);
}
I want to receive filtered list of options instead of all model rows.
You can do this easily by overriding the blades in voyager:
Step 1 :
Copy relationship.blade.php
from: /"YourProject"/vendor/tcg/voyager/resources/views/formfields/relationship.blade.php
To: /"YourProject"/resources/views/vendor/voyager/formfields/relationship.blade.php
This way voyager will use this file in your your project views instead of the package file in the vendor.
Read More: Voyager Documentations
Step 2 :
In the line 25 of relationship.blade.php you'll see this block of code:
<select
class="form-control select2-ajax" name="{{ $options->column }}"
data-get-items-route="{{route('voyager.' . $dataType->slug.'.relation')}}"
data-get-items-field="{{$row->field}}"
>
#php
$model = app($options->model);
$query = $model::where($options->key, $dataTypeContent->{$options->column})->get();
#endphp
#if(!$row->required)
<option value="">{{__('voyager::generic.none')}}</option>
#endif
#foreach($query as $relationshipData)
<option value="{{ $relationshipData->{$options->key} }}" #if($dataTypeContent->{$options->column} == $relationshipData->{$options->key}){{ 'selected="selected"' }}#endif>{{ $relationshipData->{$options->label} }}</option>
#endforeach
</select>
Which you should override it with this:
#if($options->table == 'categories')
<div class="ap-form-input">
#php
$model = app($options->model);
$query = $model::where('active', true)->get();
#endphp
<select class="form-control select2" id="language-select" name="{{ $options->column }}">
#if(!$row->required)
<option value="">{{__('voyager::generic.none')}}</option>
#endif
#foreach($query as $relationshipData)
<option value={{ $relationshipData->{$options->key} }} #if($dataTypeContent->{$options->column} == $relationshipData->{$options->key}){{ 'selected="selected"' }}#endif>{{ $relationshipData->{$options->label} }}</option>
#endforeach
</select>
</div>
#else
<div class="ap-form-input">
<select class="form-control select2" name="{{ $options->column }}">
#php
$model = app($options->model);
$query = $model::all();
#endphp
#if(!$row->required)
<option value="">{{__('voyager::generic.none')}}</option>
#endif
#foreach($query as $relationshipData)
<option value={{ $relationshipData->{$options->key} }} #if($dataTypeContent->{$options->column} == $relationshipData->{$options->key}){{ 'selected="selected"' }}#endif>{{ $relationshipData->{$options->label} }}</option>
#endforeach
</select>
</div>
#endif
This way when you're using categories relationship you will only get the active categories.
Click on the link and follow these simple steps, just now I solved my issue.
https://voyager.readme.io/docs/relationships

How to show old data of select element

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.

Resources