How do i assign the 'value' on the Laravel Form Builder Select Options dynamically in my views?
Example:
Function
public function create()
{
$categories = \DB::table('categories')->pluck('name', 'id');
return view('link.create')->with('categories', $categories);
}
View
<div class="form-group">
{!! Form::label('Link Category') !!}<br />
{!! Form::select('category',
(['0' => 'Select a Category'] + $categories),
null,
['class' => 'form-control']) !!}
</div>
Result
<select name="category" class="form-control">
<option value="0">Select a Category</option>
<option value="1">Laravel</option>
<option value="2">Zend Framework</option>
<option value="3">CakePHP</option>
<option value="4">PHP</option>
</select>
I would like the 'value' of the Select Options to be identical to the Option Content.
Like:
<option value="1">Laravel</option>
Should be like:
<option value="Laravel">Laravel</option>
If you pluck only the name, you can do something like this:
public function create()
{
$categories = \DB::table('categories')->pluck('name');
// creates ['Laravel' => 'Laravel', 'PHP' => 'PHP'...]
$categories = array_combine($categories, $categories);
return view('link.create')->with('categories', $categories);
}
You can just pluck name for both key and value
public function create()
{
$categories = \DB::table('categories')->pluck('name', 'name');
// Combine your default item
$categories = ['0' => 'Select a Category'] + collect($categories)->toArray();
return view('link.create')->with('categories', $categories);
}
Your view modified as below
<div class="form-group">
{!! Form::label('Link Category') !!}<br />
{!! Form::select('category', $categories, null, ['class' => 'form-control']) !!}
</div>
Related
I´m trying to create a form select in laravel.
I was created perfectly, but in my view first option is 0 and one first option empty
I need to remove this 0 and option empty, but i don't know how i can do it, this is my actual code:
<div class="form-group row ">
{!! Form::label('restaurant_id', trans("lang.blog_restaurant_id"),['class' => 'col-3 control-label text-right']) !!}
<div class="col-9">
{!! Form::select('restaurant_id', [null => null, $restaurant], null, ['class' => 'select2 form-control']) !!}
<div class="form-text text-muted">{{ trans("lang.blog_restaurant_id_help") }}</div>
</div>
</div>
$restaurant it's one data array for to fill my select. I read that with first option null put selected option empty, but generate a empty option and 0.
Thanks for help me.
UPDATE
Laravel include optgroup into Form::select that it´s triggering my 0 this it´s the problem. i need delete optgroup
<select class="select2 form-control select2-hidden-accessible" id="restaurant_id" name="restaurant_id" tabindex="-1" aria-hidden="true">
<option value="" selected="selected"></option>
<optgroup label="0">
<option value="17">Foody Lindgren, Cremin and Erdman gdfgfg fgfg fg fgfg g fggf</option>
<option value="28">restaurante de pruebas</option>
<option value="29">probando</option>
<option value="30">pincho de castilla2</option>
</optgroup>
update 2
getting list of restaurant:
$restaurant = $this->restaurantRepository->pluck('name', 'id');
this is result in blade:
{"17":"Foody Lindgren, Cremin and Erdman gdfgfg fgfg fg fgfg g fggf","28":"restaurante de pruebas","29":"probando","30":"pincho de castilla2"}
Add toArray():
$restaurant = $this->restaurantRepository->pluck('name', 'id');
$restaurant->toArray();
same result
Please try this. Add blank key and blank value like below.
{!! Form::select('restaurant_id', ["" => "", $restaurant], null, ['class' => 'select2 form-control']) !!}
It seems that the $restaurant is an array.
So, you'd better do something like this:
Form::select('restaurant_id', $restaurant, null, ['class' => 'select2 form-control'])
you may need a proper mapping for your $restaurant in your controller, depending on what you need, like adding an empty option in the beginning.
// in Controller
$options = ["" => "select"] + $restaurant;
// In view
Form::select('restaurant_id', $options, null, ['class' => 'select2 form-control'])
update 2
You should make sure to send the $restaurant as an array:
$restaurant = $this->restaurantRepository->pluck('name', 'id')->toArray();
For adding an empty option:
$restaurant = ["" => "select"] + $restaurant;
There is also another option:
You can even add the select box manually instead of using Form::select.
<select class="select2 form-control" id="restaurant_id" name="restaurant_id">
<option value="" selected="selected"></option>
#foreach($restaurant as $value => $option)
<option value="{{ $value }}">{{ $option }}</option>
#endforeach
</select>
i'd like to save data from multiple select to the database. So a user can choose more than one products in a multiple select. I've tried the code like below but i got this error "ErrorException Array to string conversion".
Here is my blade.php
<div class="form-group row" style="display:none;" id="inputbarang">
<label class="col-form-label col-lg-3 col-sm-12">Barang</label>
<div class="col-lg-4 col-md-9 col-sm-12">
<select class="form-control m-select2" width="500px" id="kt_select2_1" name="id_product[]" multiple="multiple">
<option value=""></option>
#foreach($produk as $p)
<option value="{{ $p->id }}">{{ $p->product }}</option>
#endforeach
</select>
</div>
</div>
and here is my controller
$id_promo = Promo::select('id')
->where('delete', 0)->orderBy('created_at', 'DESC')
// ->take(1)
->pluck('id')->first();
$id_product = [];
$id_product[] = $request->id_product;
// $id_products = $id_product['id_product'];
foreach ($id_product as $i) {
DetailPromo::create([
'id_promo' => $id_promo,
'id_product' => $i,
'det_potongan' => $request->potongan,
'det_jumlah_potongan' => $request->jumlah_potongan
]);
}
Any helps will be appreciated, thank you so much
Try below code:
$id_promo = Promo::select('id')
->where('delete', 0)
->orderBy('created_at', 'DESC')
// ->take(1)
->pluck('id')
->first()
;
$id_products = $request->id_product;
foreach ($id_products as $id_product) {
DetailPromo::create([
'id_promo' => $id_promo,
'id_product' => $id_product,
'det_potongan' => $request->potongan,
'det_jumlah_potongan' => $request->jumlah_potongan
]);
}
I need to send e.g. 5 records in one query into the one table (id_book - is every time different), so I need to by one click on button, create e.g. 10 records. This code shows this Error message:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id_book.0' in 'where clause' (SQL: select count() as aggregate from connect_user_books where id_book.0 = 6* (MY TEXT: 6 IS ID OF MY LIST INTO WHICH I NEED TO ADD THEASE RECORDS))
My controller:
public function create()
{
$books = Book::all();
return view('connectUserBook.create', compact('books'));
}
public function store(Request $request)
{
$this->validate($request, [
'id_user_select' => 'required',
'id_book' => 'required|array',
'id_book.*' => 'exists:connect_user_books',
]);
$userId = $request->input('id_user_select');
// Vytvoření
foreach ($request->input('id_book') as $book) {
$connect = new ConnectUserBook;
$connect->id_user_select = $userId;
$connect->id_book = $book;
$connect->save();
}
return redirect('/dashboard')->with('success', 'Výběr editován!');
}
My HTML markup:
{{ Form::open(['action' => 'ConnectUserBookController#store', 'method' => 'POST']) }}
<div>
<label class="form-label">Vybraný výběr *</label>
<div>
<select name="id_user_select" class="form-control">
<?php
$select_id = $_GET["id"];
$select_id;
$res = mysqli_query($link, "select * from selected_books Where id = $select_id");
while($row = mysqli_fetch_array($res))
{
?>
<option value="<?php echo $row["id"]; ?>"> <?php echo $row["title"]; ?></option>
<?php
}
?>
</select>
</div>
</div>
<br>
#for ($i = 0; $i < 11; $i++)
<div>
<label class="form-label">Book {{ $i }} *</label>
<div>
<select name="id_book[]" class="form-control">
#foreach ($books as $book)
<option value="{{ $book->id_book }}">{{ $book->nazev }} - {{ $book->pocet_stranek }} stran</option>
#endforeach
</select>
</div>
</div>
#endfor
{{Form::submit('Submit', ['class' => 'btn btn-primary'])}}
{{ Form::close() }}
Make an array and use the insert method with eloquent.
$data = array()
foreach ($request->input('id_book') as $book) {
$data[] = array('id_user_select'=>$userId,'id_book'=>$book);
}
ConnectUserBook::insert($data);
as per your error your need to specify with the column. add a column to compare with which column exists?
'id_book.*' => 'exists:connect_user_books,column_name',
Note :- It doesn't insert the timestamps.
I have a form where i search for products on a few subjects, i also have a html select working with a php switch to enable the ability to sort the order of the results. this currently works in the search form and i want to make the sort by html select to work without clicking the the search button and to run the correct select option every time its changed and to instantly change the order of the products to match the select option.
Here is the HTML:
{!! Form::open(['route' => 's.index', 'method' => 'GET']) !!}
<div class="form-group">
{!! Form::label('productsname', 'Search By Name:') !!}
{!! Form::text('productsname', null, array('class' => 'form-control')) !!}
</div>
</div>
<div class="col-md-6">
<div class="form-group">
{!! Form::label('categories_id', 'Search By Category:') !!}
<select class="form-control" name="categories_id" >
<option value=""></option>
#foreach($types as $type)
<option value="{{$type->id}}">{{$type->name}}</option>
#endforeach
</select>
</div>
</div>
<div class = col-md-6>
<div class="form-group">
</div>
</div>
<div class="form-group">
<select class="form-control" name="SortbyList" >
<option value="1">Highest Avg</option>
<option value="2">Lowest Avg</option>
<option value="3">Another Sort option</option>
<option value="2">another sort option</option>
</select>
{!! Form::submit('Find Products', array('class' => ' btn-lg btn-block')) !!}
{!! Form::close() !!}
</div>
Here is the PHP:
public function index(Request $request)
{
//
$productsQuery = Product::where('approved', '=', 1)->leftJoin('reviews', 'reviews.products_id', '=', 'products.id')->select('products.*', DB::raw('AVG(ratings) as ratings_average' ))->groupBy('products.id');
switch ($request->SortbyList) {
case 1:
$productsQuery = $productsQuery->orderBy('ratings_average', 'DESC');
break;
case 2:
$productsQuery = $productsQuery->orderBy('ratings_average', 'ASC');
break;
case 3:
$productsQuery = $productsQuery->orderBy('ratings_average', 'ASC');
break;
case 4:
$productsQuery = $productsQuery->orderBy('ratings_average', 'ASC');
break;
default:
$productsQuery = $productsQuery->orderBy('ratings_average', 'DESC');
}
$name=$request->input('productname');
$location=$request->input('categories_id');
if(!empty($name)){
$sightsQuery->where('productname', 'LIKE', '%'.$name.'%')->get();
}
if(!empty($location)){
$sightsQuery->where('categories_id', $request->input('categories_id') )->get();
}
$products= $productsQuery->paginate(8);
return view('p.search')->withproducts($products);
}
If I understood correctly, you want to change the order without clicking on the submit button (and so, without changing/reloading the page)?
PHP can not dynamically update your page, but Javascript can.
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() }}