How can I set the default value Laravel <select> element? - laravel-5.8

I want to retrieve database values in category name and i want to show default value in selection. This is my controller for my edit view.
I have a category_product table.
<div class="col-md-4">
<div class="form-group">
<label for="category">category</label>
<select class="form-control" name="category" id="category">
#foreach($categories as $category)
<option value="{{ $category->id }}" {{ $product->categories()->category_id == $category->id ? 'selected' : '' }}>{{ $category->name }}</option>
#endforeach
</select>
</div>
</div>
ProductController.php
public function edit(Product $product)
{
$categories = Category::all();
return view('Admin.products.edit', compact('product', 'categories'));
}
Product.php
public function categories()
{
return $this->belongsToMany(Category::class);
}
I get this error.
Undefined property: Illuminate\Database\Eloquent\Relations\BelongsToMany::$category_id

You need to add default value in the select tag above foreach() loop.
<div class="col-md-4">
<div class="form-group">
<label for="category">category</label>
<select class="form-control" name="category" id="category">
<option value="xyz">xyz</option> /* set default option value */
#foreach($categories as $category)
<option value="{{ $category->id }}" {{$category->id == $category->id ? 'selected' : '' }}>{{ $category->name }}</option>
#endforeach
</select>
</div>
</div>
If you want set category name selected then you need to match category in product collection. ( if you have catetory_id in product table )
<select class="form-control" name="category" id="category">
#foreach($categories as $category)
<option value="{{ $category->id }}" {{$product->catetory_id == $category->id ? 'selected' : '' }}>{{ $category->name }}</option>
#endforeach
</select>

Related

Show selected category

How can i show in my edit.blade.php the selected category of my product. you can only choose 1 category so is not many to many relation.
Product model :
public function category(){
return $this->belongsTo(Category::class);
}
Category model :
public function products(){
return $this->hasMany(Product::class);
}
Db products:
<div class="form-group my-2">
<label for="category">Choose Category :</label>
<select name="category_id" class="form-control custom-select">
#foreach($categories as $category)
<option value="{{$category->id}}" #if($product->category->contains($category->id)) selected #endif>{{$category->name}}</option>
#endforeach
</select>
</div>
I keep getting errors like :
Call to undefined method App\Models\Category::contains()
Laravel version < 9
<option value="{{ $category->id }}" {{ ($product->category_id == $category->id) ? 'selected' : '' }}>{{ $category->name }}</option>
Larvel version > 9
<option value="{{ $category->id }}" #selected($product->category_id == $category->id)>{{ $category->name }}</option>
Ref: https://laravel.com/docs/9.x/blade#checked-and-selected
Your product belongsTo category:
<option value="{{$category->id}}" #if($product->category_id == $category->id) selected #endif>{{$category->name}}</option>
You could try this
<option value="{{$category->id}}" {{($product->category_id == $category->id) ? 'selected' : ''}}>{{$category->name}}</option>

How get old value on select in laravel blade?

i have filter form using select dropdown , but i cant get this old value after i submit this filter like input like type text . someone can help ?
<div class="form-group">
<label>Status</label>
<select class="form-control select2 select2-hidden-accessible" style="width: 100%;" data-select2-id="1" tabindex="-1" aria-hidden="true"
name="user_id" id="user_id" required
>
#foreach($unit as $id => $nama_unit )
<option value="{{ $id }}">{{ $nama_unit }}</option>
#endforeach
</select>
<div class="help-block with-errors"></div>
</div>
i add my function controller :
public function search_filter_alkes(Request $request)
{
$unit = User::where('roles_id' , 1)->pluck('nama_unit', 'id');
$user_id = $request->user_id;
$alat = Alat::with('users')->where('user_id',$user_id)
->where('jenis', 'Alkes')->
get();
session()->put('user_id',$user_id);
return view('sarpras.alkes',['user_id' => $user_id , 'unit' => $unit,'alat' => $alat ])
->with('user_id', $user_id)
;
}
as per your code use this and make sure you use withInput()
return redirect()->back()->withErrors($validator)->withInput();
<div class="form-group">
<label>Status</label>
<select class="form-control select2 select2-hidden-accessible" style="width: 100%;" data-select2-id="1" tabindex="-1" aria-hidden="true"
name="user_id" id="user_id" required
>
#foreach($unit as $id => $nama_unit )
<option value="{{ $id }}" {{ old('user_id') == $id ? "selected" :""}}>{{ $nama_unit }}</option>
#endforeach
</select>
<div class="help-block with-errors"></div>
</div>
EDITED
When you use redirect() after post method you have to use withInput() as i mention above example
return redirect('route')->withInput();
when you use view() you have to pass data like as array like your code then use same variable name
return view('sarpras.alkes',['user_id' => $user_id , 'unit' => $unit,'alat' => $alat ])
<option value="{{ $id }}" {{ $user_id == $id ? "selected" :""}}>{{ $nama_unit }}</option>
You wil have to compare old value with input key. So replace the below code inside your for loop
#if (Input::old('user_id') == $id)
<option value="{{ $id }}" selected>{{ $nama_unit }}</option>
#else
<option value="{{ $id }}">{{ $nama_unit }}</option>
#endif
You have multiple options:
<select name="tags[]" class="form-control select-tag" multiple>
#foreach($tags as $tag)
<option value="{{$tag->id}}" {{in_array($tag->id, old("tags") ?: []) ? "selected": ""}}>{{$tag->name}}</option>
#endforeach
</select>
OR
<select name="gender" class="form-control" id="gender">
<option value="">Select Gender</option>
<option value="M" #if (old('gender') == "M") {{ 'selected' }} #endif>Male</option>
<option value="F" #if (old('gender') == "F") {{ 'selected' }} #endif>Female</option>
</select>
This worked for me in laravel 8:
<select class="form-control" id="gender" name="gender" required>
<option value="">Select gender</option>
<option value="M" #if (old('gender') == "M") {{ 'selected' }} #endif>Male</option>
<option value="F" #if (old('gender') == "F") {{ 'selected' }} #endif>Female</option>
<option value="O" #if (old('gender') == "O") {{ 'selected' }} #endif>Other</option>
</select>

How can I show the old value in option fields in Laravel?

I want to show the old select value in this select field when I want to edit. How can I show my old value in these fields?
https://github.com/shakibzaman/book-library-laravel
you can show my GitHub repo-
Here is my rules edit page:
<div class="form-group {{ $errors->has('name') ? 'has-error' : '' }}">
<label for="chap_id">{{ trans('cruds.chapters.title_singular') }}*</label>
<select name="chap_id" id="chap_id" class="form-control select2">
#foreach($chapters as $id => $chapter)
<option value="{{ $id }}">{{ $chapter }}</option>
#endforeach
</select>
#if($errors->has('name'))
<em class="invalid-feedback">
{{ $errors->first('name') }}
</em>
#endif
<p class="helper-block">
{{ trans('cruds.permission.fields.title_helper') }}
</p>
</div>
editController
public function edit($id)
{
if (!Gate::allows('users_manage')) {
return abort(401);
}
$rule = Rule::find($id);
$chapters = Chapter::all()->pluck('name', 'id')->prepend(trans('global.pleaseSelect'), '');
return view('admin.rules.edit', compact('rule', 'chapters'));
}
You can use the old() function to get the old value of a field. This function requires one input and that is the name of the field: old('chap_id').
You could use this one:
#foreach($chapters as $id => $chapter)
#if(null !== old('chap_id') && old('chap_id') === $id)
<option value="{{ $id }}" selected>{{ $chapter }}</option>
#else
<option value="{{ $id }}">{{ $chapter }}</option>
#endif
#endforeach
Or the shorter one:
#foreach($chapters as $id => $chapter)
<option value="{{ $id }}" {{ old('chap_id') === $id ? 'selected' : '' }}>{{ $chapter }}</option>
#endforeach

How to show default value in select option (parent_id)?

I tried to save a parent_id of Category in Laravel 5.8 successfully, but I want to edit category now.
CategoryController.php
public function edit(Category $category)
{
return view('Admin.categories.edit', compact('category'));
}
public function update(CategoryRequest $request, Category $category)
{
$category->update($request->all());
return redirect(route('categories.index'));
}
edit.blade.php
<form action="{{ route('categories.update', $category->id) }}" method="post">
{{ method_field('PATCH') }}
{{ csrf_field() }}
#include('Admin.layouts.errors')
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" value="{{ old('name') ? : $category->name }}" id="name" name="name">
</div>
<div class="form-group">
<label for="parent_id">Sub Category</label>
<select class="form-control" id="parent_id" name="parent_id" data-live-search="true">
#foreach(\App\Category::all() as $category)
<option value="{{ $category->id }}" {{ trim($category->id) , $category->pluck('id')->toArray() ? 'selected' : '' }}>{{ $category->name }}</option>
#endforeach
</select>
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
For example, I have the following categories in the database.
id name parent_id
1 Software 0
2 Hardware 0
3 Photoshop 1
4 CoredDraw 1
If a user, for example, selects CorelDraw for edit, open edit for it. Select the name input tag, write CorelDraw. Select the parent_id option tag select Software. Because this is parent_id is = 0.
You need to do some basic improvement in your code, Make a practice of fire query in the model or in the controller
Blade file is not for load the data from the database
Controller
public function edit(Category $category)
{
$allCategory = \App\Category::all();
return view('Admin.categories.edit', compact('category','allCategory'));
}
Blade
<select class="form-control" id="parent_id" name="parent_id" data-live-search="true">
<option value="">Select Parent</option>
#foreach($allCategory as $cate)
<option value="{{ $cate->id }}" {{ $category->id == $cate->id ? 'selected' : '' }}>{{ $cate->name }}</option>
#endforeach
</select>
Once the user starts typing different category name you need to reset the select box using any client side script

How to use isset in select option in laravel form

How to use isset if i use select option?
Please help.
This is how i use to get my data for normal insert.
<div class="form-group">
<label>Zone Name</label>
<input type="text" name="name" class="form-control" value="{{ old('name',isset($zone) ? $zone->name : '') }}" placeholder="Name">
</div>
But i don't know how to use isset in select option.
<div class="form-group">
<label>Select Country</label>
<select class="form-control" name="country_id">
<option value="" selected>Please Select</option>
#if ($country->count())
#foreach($country as $c)
<option value="{{ $c->country_id }}" {{ $selectCountry == $c->country_id ? : '' }}>{{ $c->name }}</option>
#endforeach
#endif
</select>
</div>
This is my Controller
public function edit(Request $request, $id){
$zone = Zone::find($id);
$country = Country::all();
$selectCountry= Country::first()->country_id;
if(!$zone){
return redirect('/');
}
return view('zone.edit',['zone' => $zone, 'country'=>$country, 'selectCountry'=>$selectCountry]);
}
my expected result is when i press on edit button, it will show the previous selected result.
You can write
<select class="form-control" name="country_id">
<option value="" {{ !isset($selectCountry) ? 'selected' : '' }}>Please Select</option>
#if ($country->count())
#foreach($country as $c)
<option value="{{ $c->country_id }}" {{ (isset($selectCountry) && $selectCountry == $c->country_id) ? 'selected' : '' }}>{{ $c->name }}</option>
#endforeach
#endif
</select>

Resources