laravel select box values showing - php

I made a admin panel with laravel 5.4 . I want to show my category list using category table in products items edit view page. This is my product items edit page controller.
public function edit($id)
{
$item = Item::findOrFail($id);
//$sub_cat = SubCat::all();
$sub_cat = SubCat::with('category')->get();
return view('admin.items.edit', compact(['item', 'sub_cat']));
}
And this is my product items edit page view selection box values show
<div class="form-group">
<label>Main Category</label>
<select class="form-control" id="main_category" name="main_category">
#if(!empty($sub_cat))
#foreach ($sub_cat as $pages)
<option value="{{ $item->id }}">{{ $pages->name }}</option>
#endforeach
#endif
</select>
</div>
I used a model relationship like this
public function category(){
return $this->belongsTo('App\SubCat');
}
How i show my saved category name with other category names into my selection box.

first of all get all the categories like this
public function edit($id)
{
$item = Item::findOrFail($id);
$sub_cat = SubCat::all(); //get all the categories
return view('admin.items.edit', compact(['item', 'sub_cat']));
}
in the blade file run loop on $sub_cat collection and replace $item->id to $pages->id
<div class="form-group">
<label>Main Category</label>
<select class="form-control" id="main_category" name="main_category">
#if(!empty($sub_cat))
#foreach ($sub_cat as $pages) //loop on $sub_cat
<option value="{{ $pages->id }}" {{ $item->category_id == $pages->id ? 'selected="selected"' : '' }}>{{ $pages->name }}</option>
#endforeach
#endif
</select>
</div>

Related

Determine selected options based on many-to-many relationship

I have three tables: products, categories and category_product.
In my edit form page I'm displaying the categories and subcategories values in a select box.
The chosen category options are saved in the pivot table category_product. This table has product_id and category_id.
Here's my code.
Product model
public function category() {
return $this->belongsToMany('App\Models\Category');
}
Category model:
public function products()
{
return $this->belongsToMany(Product::class);
}
edit product page view:
<select name="category_id[]" class="form-control" multiple size = 10>
#foreach ($parentCategories as $parentCategory)
<option value="{{ $parentCategory->id }}">{{ $parentCategory->name }}</option>
#if(count($parentCategory->subcategory))
#include('includes.subcats-select',['subcategories' => $parentCategory->subcategory])
#endif
#endforeach
</select>
subcats-select view
#foreach($subcategories as $subcategory)
<option value="{{ $subcategory->id }}">---{{ $subcategory->name }}</option>
#if(count($subcategory->subcategory))
#include('includes.subcats-select',['subcategories' => $subcategory->subcategory])
#endif
</div>
#endforeach
How can I put "selected" attribute to the chosen category options, so when I edit the page to apply the changes properly?
You can get pivot table columns the following way:
Product model
public function category() {
return $this->belongsToMany('App\Models\Category')->withPivot('selected');
}
edit product page View:
<select name="category_id[]" class="form-control" multiple size = 10>
#foreach ($parentCategories as $parentCategory)
<option value="{{ $parentCategory->id }}" selected="{{ $parentCategory->pivot->selected }}">
{{ $parentCategory->name }}
</option>
#if(count($parentCategory->subcategory))
#include('includes.subcats-select',['subcategories' => $parentCategory->subcategory])
#endif
#endforeach
</select>
EDIT: While the above answer might be helpful for others, it doesn't answer the question. So here's my second try after some clarification in the chat.
<select name="category_id[]" class="form-control" multiple size = 10>
#foreach ($parentCategories as $parentCategory)
<option value="{{ $parentCategory->id }}"{{ $product->category->contains($parentCategory->id) ? 'selected' : '' }}>
{{ $parentCategory->name }}
</option>
#if(count($parentCategory->subcategory))
#include('includes.subcats-select',['subcategories' => $parentCategory->subcategory])
#endif
#endforeach
</select>

how to iterate category options with edit blade file in Laravel 6

working with laravel 6 and need edit category options here.
PostController.php
public function edit($id)
{
$post = Post::find($id);
$categories = Category::all();
$cats = array();
foreach ($categories as $category) {
$cats[$category->id] = $category->name;
}
return view('posts.edit')->withPost($post)->withCategories($cats);
}
and edit.blade.php
<div class="form-group">
<label for="exampleFormControlSelect1">Category</label>
<select class="form-control" name="category_id" id="category_id">
#foreach($categories as $cats)
<option value="{{$post->category->id}}">{{$post->category->name}}</option>
#endforeach
</select>
</div>
but when I am going to edit page in the edit category options display only current category item. I need display all categories in the table? how could I manage this?
simply like this :
Controller
public function edit($id)
{
$post = Post::findOrFail($id);
$categories = Category::all();
return view('posts.edit', compact(['post', 'categories']));
}
View
<div class="form-group">
<label for="exampleFormControlSelect1">Category</label>
<select class="form-control" name="category_id" id="category_id">
#foreach($categories as $cat)
<option value="{{$cat->id}}" #if($cat->id === $post->category_id) 'selected' #endif >{{$cat->name}}</option>
#endforeach
</select>
</div>

How can I get selected value in select dom element [Laravel]

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

Undefined variable: categories in Blade Laravel 6.4.0

I am trying to show my categories on the site map page with the controller below.
CategoryController.php
class CategoriesController extends Controller
{
public function create()
{
$categories = Category
::orderBy('name','desc')
->where('parent_id', NULL)
->get();
return view('admin.category.create', compact('categories'));
}
}
The following is the part of my Blade file where I use the categories variable template.
create.blade.php
<div class="form-group">
<label for="exampleInputPassword1">Parent Category</label>
<select name="parent_id" class="form-control">
#foreach ($main_categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>
</div>
I use every way to get variable and passing but none the didn't work do you have any suggestion?
You've got two options here.
Option A:
You named the collection categories in your Controller and pass it to the view as such. To access it in your view, you need to reference it by the same name.
Change this:
// Your view is looking for a collection titled `main_categories`, which does not exist
#foreach ($main_categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
To this:
#foreach ($categories as $c)
<option value="{{ $c->id }}">{{ $c->name }}</option>
#endforeach
Option B:
Pass the data back using main_categories as the collection name
Change this:
return view('admin.category.create', compact('categories'));
To this:
return view('admin.category.create', [
'main_categories' => $categories
]);
You can read up more on passing data to views here.
To be more clear Ill break your code as below and add some details
class CategoriesController extends Controller
{
public function create()
{
$categories = Category
::orderBy('name','desc')
->where('parent_id', NULL)
->get();
// Your are passing variable but I change it as below to be more clear
// return view('admin.category.create', compact('categories'));
//now you are passing the value to the view
return view('admin.category.create', ['categories' => $categories]);
}
}
Now lets catch it in the view. Note that now $categories available in the view. If you pass ['A' => $categories] then view has $A variable so you should call for the relevant variable that you define in the controller.
<div class="form-group">
<label for="exampleInputPassword1">Parent Category</label>
<select name="parent_id" class="form-control">
**{{-- In here you should pass $categories --}}**
#foreach ($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>
</div>

Validating multiple select box inside loop using laravel validation method

I have multiple select box with same name inside loop in a form. I have added laravel validation to check select box selected or not. But validation error message is showing for all the select boxes. Please check image attached. Any help would be appreciated.
cart.blade.php
#forelse($carts as $key => $cart)
<div class="col-sm-4 col-sm-4-booking1 form-group {{ $errors->has('guest.*.sleeps') ? ' has-error' : '' }}">
<label>Sleep(s)</label>
<select class="form-control form-control-booking1 jsBookCalSleep" name="guest[{{ $cart->_id }}][sleeps]">
<option value="">Choose Sleep(s)</option>
#for($i = 1; $i <= 30; $i++)
<option value="{{ $i }}" #if($i == $cart->sleeps) selected #endif>{{ $i }}</option>
#endfor
</select>
#if ($errors->has('guest.*.sleeps'))
<span class="help-block"><strong>{{ $errors->first('guest.*.sleeps') }}</strong></span>
#endif
</div>
#empty
<p>No bookings in your cart</p>
#endforelse
CartController.php
public function store(CartRequest $request)
{
dd($request->all());
}
CartRequest.php
public function rules()
{
return [
'guest.*.sleeps' => 'required|not_in:0'
];
}
Try these
#php
$inputName='guest.'.$cart->_id.'.sleeps';
#endphp
#if ($errors->has($inputName))
<span class="help-block"><strong>{{ $errors->first($inputName) }}</strong></span>
#endif
I didn't tested it,
If not working let me know
Solution: We can solve this issue by using two function. a.collect and b. contains. See the example below.
<select class="form-control m-bootstrap-select m_selectpicker"
name="generic_ids[]" data-live-search="true" multiple>
<option value="">Select Generic</option>
#foreach($generics as $generic)
<option value="{{$generic->id}}"
#if(collect(app()->request->generic_ids)->contains($generic->id))
selected
#endif
>{{$generic->title}}</option>
#endforeach
</select>
Code
Output

Categories