Laravel Select Name and id of Model and use in SelectBox - forms

This is my current Function in my Controller:
public function addProduct()
{
$categories = Category::all();
return view('admin.products.add')->with('categories', $categories);
}
I want to only select the columns "name" and "id" from the Category Model and assign them to the selectbox in my view like this:
<select>
<option value="ID">NAME</option>
</select>
How can I do this using the Form-Facade?

try with pluck method from the laravel Collection:
$categories = Category::all()->pluck('name', 'id');
and then in the view:
{!! Form::select('name', $categories) !!}

Try this generate all category
<select name="category" class="form-control">
#foreach($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>
And if you want to set particular category selected then do this
<select name="category" class="form-control">
#foreach($categories as $category)
<option value="{{ $category->id }}" <?php if($hotel->category_id == $category->id) { echo "selected";}?>>{{ $category->name }}</option>
#endforeach
</select>

You can use foreach here
In your blade view.
<select name = "category[]">
#foreach($categories as $category)
<option value = "{{$category->id}}">{{$category->youValueHere}}></option>
#endforeach
</select>

Lists was deprecated in L5.2 and removed on L5.3
Try this, simple & neat.
$categories = Category::lists('name', 'id');
{!! Form::select('categories[]', $categories, null, [
'class' => 'form-control', 'multiple'
]) !!}

Related

insert data if not exist in the column using Laravel elequant

I'm developing a doctor's appointment laravel project. the condition is if a user fixes an appointment they can't able to fix the appointment for the same doctor at the same date and time. I tried with firstOrCreate method but doesn't match my condition. here are my conditions
1.if doctors_id AND date AND time already exist then shouldn't insert the data
2.if doctors_id OR date OR time, any three of this already exist then can insert the data
3.if all fields already not exist then insert data
here are the code snippets
In view
<div class="card-body">
<form action="appointment" method="post">
{{ #csrf_field() }}
<select name="doctors" id="" class="form-control">
#foreach ($docList as $item)
<option value="{{$item->id}}">{{$item->name}}</option>
#endforeach
</select><br><br>
<input type="date" name="date" id="" class="form-control">
<br><br>
<select name="time" class="form-control">
<option value="9-10AM">9-10AM</option>
<option value="10-11AM">10-11AM</option>
<option value="1-2PM">1-2PM</option>
<option value="2-3PM">2-3PM</option>
<option value="3-4PM">3-4PM</option>
</select>
<button type="submit" class="btn btn-primary">Fix Appointment</button>
</form>
</div>
In controller
public function store(Request $request)
{
$uId = Auth::id();
$fixAppointment = Appointment::firstOrNew(['doctors_id'=>$request->doctors,'date'=>request('date')],['time'=>request('time')]);
$fixAppointment->users_id = $uId;
$fixAppointment->save();
}
Here I sorted out the issue by using where condition
In controller
$appointment = Appointment::where('date', '=', request('date'))->where('time','=',request('time'))->where('doctors_id','=',request('doctors'))->first();
if ($appointment === null)
{
$fixAppointment = New Appointment;
$fixAppointment->doctors_id = $request->doctors;
$fixAppointment->users_id = $uId;
$fixAppointment->date = $request->date;
$fixAppointment->time=$request->time;
$fixAppointment->save();
}
here is the link which I referred to find this solution.

Vue multiple select

I would like to have multiple selections without multiple.vue librabry. I want to write it by my own. I have data like this in js:
data:
roles : [here data]
form.roles: []
And my html with Vue:
<select class="form-control required-select2" v-model="form.roles" id="roles" required>
<option v-for="role in roles" v-bind:value="role.id" v-bind:selected="form.roles.indexOf(role.id) > -1">
{{ role.display_name }}
</option>
</select>
How can I have in form.roles more than one role.id? I have to write maybe a method for this?
Do you want to do something like https://codepen.io/ittus/pen/vjdLvb
You need to add multiselect options to your select
<template>
<select class="form-control required-select2" v-model="form.roles" id="roles" multiple required>
<option v-for="role in roles" v-bind:value="role.id" v-bind:selected="form.roles.indexOf(role.id) > -1">
{{ role.display_name }}
</option>
</select>
<div>Selected: {{ form.roles }}</div>

Route Model Binding in Relationships

A store has many products is the relationship.
How to create new product, saves store_id and other product details.
The code as below.
Route is
Route::resource('stores.product', 'productcontroller');
i.e. binding model store with product route.
Model Store
class store extends Model
{
public function product()
{
return $this->hasMany(product::class);
}
}
create product View.
<form method="POST" action="/stores/{{$store->id}}/product" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
name <input type="text" name="name" />
</div>
productController#store
public function store ( store $store, Request $request )
{
$this->validate($request, [
'name' => 'required|max:255',
'detail' => 'nullable' ,
]);
$product = new product;
$product-> user_id = auth()->id();
$product-> store_id = $store->id;
$product-> name = $request->name;
$product->save();
return redirect('/stores/{{$store->id}}/product');
}
Please explain how route model binding works in relationships.
What should be my create form's method and action?
Where should productController#store return redirect?
First you have to create the inverse relation between stores and products
Like this:
class Store extends Model
{
public function products()
{
return $this->hasMany(Product::class);
}
}
class Product extends Model
{
public function store()
{
return $this->belonsTo(Store::class);
}
}
Second you have to pass all your stores to your create product page:
public function create (){
$storList = Store::all();
return view("createproductview", compact("storList"));
}
In that page you have to show the stores to select one of them, and manage your errors from the validation process:
<form method="POST" action="{ route("product.store") }}" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group {{ ($errors->has('store'))?"has-error":"" }}">
<label for="store">Store</label>
<select class="form-control" name="tipoaudiencia" id="store">
<option value="">Select one option</option>
#foreach($storList as $row)
<option {{ (old("store") == $row->id ? "selected":"") }} value="{{ $row->id }}">{{ $row->name }}</option>
#endforeach
</select>
#if($errors->has('store'))<p class="help-block">{{ $errors->first('store') }}</p>#endif
</div>
<div class="form-group required {{ ($errors->has('name'))?"has-error":"" }}">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" placeholder="name" name="name" value="{{ old('name') }}" autofocus>
#if($errors->has('name'))<p class="help-block">{{ $errors->first('name') }}</p>#endif
</div>
...
</form>
and last the store function:
public function store ( Request $request )
{
$this->validate($request, [
'name' => 'required|max:255',
'store' => 'required'
]);
$product = new Product;
$product->name = $request->name;
$store = Store::find($request->store);
$store->products()->save($product);//this saves the product and manage the relation.
return redirect('/stores/'.$store->id.'/'.$product->id);
}
Hope this help you

Angular cast select value to int

I have a form with different selects like :
<select [(ngModel)]="selected.isConnected" (ngModelChange)="formChanged()" name="etat" id="etat" class="form-control">
<option value="0">Not connected</option>
<option value="1">Connected</option>
</select>
My backend expect to receive an int in the "isConnected" attribute. Unfortunately as soon as I change the value of the select the attribute is cast to a string :
{
isConnected : "0", // 0 expected
}
For standard <input> I could use type="number" but for a <select> I'm clueless.
Is there a way to force angular 2 to cast the data to int ?
Use [ngValue] instead of "value":
<select [(ngModel)]="selected.isConnected" id="etat">
<option [ngValue]="0">Not connected</option>
<option [ngValue]="1">Connected</option>
</select>
If you want cast it within formChanged() method (Which you haven't provided yet).
You should use + symbol as shown below,
formChanged(): void {
selected.isConnected = +selected.isConnected;
...
}
No, sadly you're forced to parse it on your own in the formChanged() method, since you always get a string back from the select.
You could try it with something like this:
formChanged(): void {
selected.isConnected = parseInt(selected.isConnected);
// ...
}
You can send a Number variable to select and assign the value for that select element. Then if you want to capture the value when it changes, you can add (change) event to select and retrieve the value as shown below.
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
template: `<select value="{{isConnected}}" (change)="printConnected($event.target.value)" name="etat" id="etat" class="form-control">
<option value="0">Not connected</option>
<option value="1">Connected</option>
</select>
<div *ngIf="changed">You've selected {{isConnected}}<div>`
})
export class AppComponent {
isConnected : number = 1;
changed : boolean = false;
printConnected(value){
this.isConnected = value;
this.changed=true;
}
}
You can view an example at http://plnkr.co/edit/xO2mrTdpTGufkgXqdhYD?p=preview
I am using reactive bindings and do not want to use [(ngModel)]. Instead I created a piped observable that uses JSON.parse(value) (because +value doesn't handle "null"):
*.component.html:
<div class="col-lg-4 form-group">
<label>Group Type</label>
<select class="form-control" (change)="groupType$.next($event.target.value)">
<option [value]="null"></option>
<option *ngFor="let groupType of filterData.groupTypes" [value]="groupType.id">{{groupType.label}}</option>
</select>
</div>
<div class="col-lg-4 form-group" *ngIf="filteredGroups$ | async as groupOptions">
<label>Group</label>
<select class="form-control" (change)="group$.next($event.target.value)">
<option [value]="null"></option>
<option *ngFor="let group of groupOptions" [value]="group.id">{{group.label}}</option>
</select>
</div>
<div class="col-lg-4 form-group">
<label>Status</label>
<select class="form-control" (change)="status$.next($event.target.value)">
<option [value]="null"></option>
<option *ngFor="let status of filterData.statuses" [value]="status.id">{{status.label}}</option>
</select>
</div>
*.component.ts:
group$ = new BehaviorSubject<string>(null);
groupId$ = this.group$.pipe(
map((groupId: string) => JSON.parse(groupId) as number)
);
groupType$ = new BehaviorSubject<string>(null);
groupTypeId$ = this.groupType$.pipe(
map((typeId: string) => JSON.parse(typeId) as number)
);
status$ = new BehaviorSubject<string>(null);
statusId$ = this.status$.pipe(
map((statusId: string) => JSON.parse(statusId) as number)
);
[ngValue] is intended for objects. It generates an artificial option value even for numeric constants. For those who might be concerned about tests or readability, you can expand two way binding microsyntax
<select [ngModel]="selected.isConnected"
(ngModelChange)="selected.isConnected=$event && +$event" id="etat">
<option value="0">Not connected</option>
<option value="1">Connected</option>
</select>

Laravel - Select defaulting to using Optgroup

I want to use a dropdown list in my view in laravel. In my controller I have the following.
$awards = array(
'gold' => 'gold',
'silver' => 'silver',
'bronze' => 'bronze',
'no-award' => 'No Award'
);
$entry->awards = $awards;
I pass it to the view as follows
$this->layout = View::make('entries/edit', array('entry' => $entry));
Finally in the view
<div class="form-group">
{{ Form::label('awards', 'Award:', array('class' => 'control-label '))}}
{{ Form::select('awards', array(entry->$awards))}}
</div>
The issue Im running into is in the source it looks like this...
<div class="form-group">
<label for="awards" class="control-label ">Award:</label>
<select id="awards" name="awards">
<optgroup label="0">
<option value="gold">gold</option>
<option value="silver">silver</option>
<option value="bronze">bronze</option>
<option value="no-award">No Award</option>
</optgroup>
</select>
</div>
Which looks good except I don't know how to avoid having it put in an optgroup, and I'd like to keep the array to my controller. Thanks.
You are wrapping your awards inside an extra unnecessary array - creating the optgroup[0]
Change
{{ Form::select('awards', array(entry->$awards)) }}
to
{{ Form::select('awards', entry->$awards) }}