I can't manage to repopulate a Select field input after a query, using Laravel 4:
// Route
Route::get('blog', 'BlogController#getPosts');
// BlogController
public function getPosts()
{
$posts = Post::where('category_id', Input::get('category'))->paginate(25);
$categories = Category::lists('title', 'id');
return View::make('blog', compact('categories', 'posts'));
}
// Blog view
{{ Form::open('method' => 'get', 'id' => 'form-search') }}
{{ Form::select('category', $categories, Input::old('category')) }}
{{ Form::close() }}
I managed to make it work this way, but it's not the best practice
<select name="category" id="category">
<option value="1" {{ (Input::get('category') == 1) ? 'selected="selected"' : null }}>Category 1</option>
<option value="2" {{ (Input::get('category') == 2) ? 'selected="selected"' : null }}>Category 2</option>
<option value="3" {{ (Input::get('category') == 3) ? 'selected="selected"' : null }}>Category 3</option>
</select>
I think the Input::old('category') doesn't work because it is a GET request, am I right? Is there any workarounds?
Update : I finally made it work using Input::get() instead of Input::old() :
{{ Form::select('category', $categories, Input::get('category')) }}
It seems you're not even retrieving the old input, you will need to pass it to the view. You can do that in one of two ways, the easiest and best to understand is to just specify that you want to pass input.
return View::make('blog', compact('categories', 'posts'))->withInput();
Also, you don't need the markup in your HTML. Laravel will do this for you if you just give it the value of the old Input. It works very well.
Perhaps this will work
public function getPosts()
{
$category_id = Input::get('category');
$posts = Post::where('category_id', $category_id)->paginate(25);
$categories = Category::lists('title', 'id');
return View::make('blog', compact('categories', 'posts', 'category_id'));
}
// Blog view
{{ Form::open('method' => 'get', 'id' => 'form-search') }}
{{ Form::select('category', $categories, $category_id) }}
{{ Form::close() }}
Related
Can someone tell me how can I get selected value when I try to edit post in Laravel project.
So here are parts of code
Post.php:
public function category(){
return $this->belongsTo('App\Category');
}
Category.php:
public function posts(){
return $this->hasMany('App\Post');
}
PostController.php:
$post = Post::findOrFail($id);
$categories = Category::all();
$tags = Tag::all();
return view('admin.posts.edit', ['post' => $post, 'categories' => $categories, 'tags' => $tags]);
posts/edit.blade.php:
<div class="form-group">
<label for="category_id">Selecet category</label>
<select name="category_id" id="category_id" class="form-control">
<option disabled>List of available post categories</option>
#foreach($categories as $category)
<option value="{{ $category->id }}" {{$category->id == $category->id ? 'selected' : '' }}>{{ $category->name }}</option>
#endforeach
</select>
</div>
Like #Hardood mentioned. $category->id == $category->id will always return true. In fact, if you just want to get the value from form submission. You can just remove that. HTML will handle selected value itself.
You can simply use $request->category_name in your backend.
Problem solved with this part of code (for future users who will read this :) )
#foreach($categories as $category)
<option value="{{ $category->id }}"
#if($post->category->id == $category->id)
selected
#endif
>{{ $category->name }}</option>
#endforeach
I found a bug when i try to displayed data on select2 tag. I got duplicate data and I want to know how to fixed it. Im using laravel 7 and here's my code
This is my controller code:
public function editLocation(Request $request,$id){
$mtFasilitas = DB::table('MT_Facility')->select('id','name')
->get();
$trFasilitas = DB::table('TR_Fasilitas')->select('idMtFasilitas')
->where('idDetailLokasi',$id)
->get();
return view('layout.back.content_kos.edit_kos',['mtFas' => $mtFasilitas, 'trFas' => $trFasilitas]);
}
This is my blade template :
<select class="js-example-basic-multiple form-control mb-4" name="fasilitas[]" multiple="multiple">
#foreach ($mtFas as $key => $data)
#foreach ($trFas as $key2 => $data2)
<option value="{{$data->id}}"{{$data2->idMtFasilitas == $data->id ? 'selected="selected"' : ''}}> {{ $data->name}}</option>
#endforeach
#endforeach
</select>
And this is the result :
enter image description here
Anyone can help me ?
Thank you
$trFasilitas = DB::table('TR_Fasilitas')->select('idMtFasilitas')
->where('idDetailLokasi',$id)
->get()
->pluck('idMtFasilitas')
->all();
<select class="js-example-basic-multiple" name="fasilitas[]" multiple="multiple">
#foreach ($mtFas as $data)
<option value="{{ $data->id }}" {{in_array($data->id, $trFas) ? 'selected="selected"' : '' : ''}}>
{{ $data->name }}</option>
#endforeach
</select>
I think this should do.
This is the result of your updated answer sir #Andy Song
As per your data
$mtFasilitas = [{"id":4,"name":"a"},{"id":5,"name":"b"},{"id":6,"name":"c"}]
$trFasilitas = [{"idMtFasilitas":4},{"idMtFasilitas":5}]
Your inner loop running twice for each single value of outer loop, thats why data printed twice.
I want to to use foreach loop in select form. But I dont figure out how can I do that.
I searched about it in here, in other questions and found lists method. But when I tried it retuns me "Call to undefined method App\Category::lists()" error.
{{ Form::select('categories',
"foreach loop" for bringing categories
) }}
Any advice ?
As discribed in the Laravel Recipes :
If you use this :
{{ Form::select('age', ['Under 18', '19 to 30', 'Over 30']) }}
You will get this output :
<select name="age">
<option value="0">Under 18</option>
<option value="1">19 to 30</option>
<option value="2">Over 30</option>
</select>
So in your case you can use it like this :
{{ Form::select('categories', $categories->pluck('name')) }}
If you want to addthe id of the category as value of the option you can do it like this :
In the controller :
$categories = [''=>''] + Category::lists('name', 'id')->all();
return view('back.create')->withCategories($categories);
And in the view :
{{ Form::select('categories', $categories) }}
I want to make when user search by country on the page refresh eg. result page to keep selected country on the option on the form.
This is what I have where I populate the dropdown
#foreach ($countries as $country)
<option value="{!! $country->id !!}">{!! $country->name !!}</option>
#endforeach
And this is what I have tried but seems that is not correct since the value isn't selected
#foreach ($countries as $country)
<option value="{!! $country->id !!}" #if( old('country->id') == $country->id) selected="selected" #endif>{!! $country->name !!}</option>
#endforeach
What's the trick here?
Here is the controller
public function search(Request $request)
{
$searchText = strip_tags($request['q']);
$seachLocation = strip_tags($request['l']);
$columns =['alias','description','address1','address2','address3'];
$query = Item::select('*');
$query->where( 'title', 'like', '%'.$searchText.'%');
foreach( $columns as $column) {
$query->orWhere( $column, 'like', '%'.$searchText.'%', '%'.$seachLocation.'%');
}
$query->orWhereHas('category',function( $query ) use ( $searchText ) {
$query->where('title', 'like', '%'.$searchText.'%' );
});
$query->orWhereHas('country',function( $query ) use ( $searchText ) {
$query->where('name', 'like', '%'.$searchText.'%' );
});
$items = $query->paginate(5);
$searchQuery = $searchText;
$searchQueryLoc = $seachLocation;
return view('search', compact('items','searchQuery','seachLocation'));
}
To use the old() helper, your form inputs need to have a name.
You then use the name of the input as the parameter in the old() helper to get the old value.
So using it like old('country->id') won't work; you need to use old('nameAttributeOfInput').
A full example assuming the name attribute of this input is country_id:
#foreach ($countries as $country)
<option value="{!! $country->id !!}" #if( old('country_id') == $country->id) selected="selected" #endif>{!! $country->name !!}</option>
#endforeach
As a side note, just be aware that {!! !!} does not escape the value being placed on the page which can be potentially dangerous. You would probably be just as fine, and safer, to use {{ }} which escapes the value.
I would suggest that you use session to store the selected country. For example:
session()->put('forms.country', $request->get('country'));
Then your html should become:
<option value="{{ $country->id }}" #if( session('forms.country') == $country->id) selected="selected" #endif>{{ $country->name }}</option>
You can use Laravel inbuilt old() in form's field to hold the provided value.
#if( old('field_name') == $country->id) selected="selected" #endif
Controller method:
public function edit($id){
$match2 = Match::pluck('team_a_id', 'id');
return view('admin.accept.edit', compact('match2'));
}
And view file:
{{ Form::select('matches_id', $match2, null, ['class' => 'form-control']) }}
And my table:
Table from model Match (table name: matches):
Table from model Team (table name: teams):
Table teams is connected (references) with table matches( team_a_id and team_b_id is connected with table teams). The select method with view returned me only ID with tables:
I need have team_name with table teams not id.
When I change method pluck:
$match2 = Match::pluck('id', 'id');
And view:
{{ Form::select('matches_id', Team::find($match2)->team_a_id." vs. ".Team::find($match2)->team_b_id, null, ['class' => 'form-control']) }}
Laravel returned error:
Invalid argument supplied for foreach() (View:
C:\xampp\htdocs\football\football\resources\views\admin\accept\edit.blade.php)
This is metohd edit so I must have highlighted record that was previously selected.
Ok I repair this. I write method:
public function edit($id){
$match = Match::select()->orderBy('updated_at', 'asc')->get();
$selectedMatch = DB::table('usermatches')->find($id)->matches_id;
return view('admin.accept.edit', compact('match', 'selectedMatch'));
}
And view:
<select name="matches_id" id="matches_id" class="form-control selectpicker" data-live-search="true" data-size="5">
<option value=0>Wybierz wydarzenie</option>
#foreach($match as $role)
<option value="{{ $role->id }}" {{ $selectedMatch == $role->id ? 'selected="selected"' : '' }}>
{{ Team::find($role->team_a_id)->team_name }} vs. {{ Team::find($role->team_b_id)->team_name }} ({{$role->date}}; <?php echo date('G:i',strtotime($role->time)); ?> | Liga {{ League::find($role->league_id)->name }} | {{ Sport::find($role->sport_id)->name }})
</option>
#endforeach
</select>
In model view I compare id with two tables and it working ;)
{{ $selectedMatch == $role->id ? 'selected="selected"' : '' }}