Can't send collection to bootstrap-select in Laravel form - php

Here is an edit form I've created
#extends('main')
#section('title', 'Edit Post')
#section('content')
<form class="form-group" action="/categories/update" method="POST">
{{csrf_field()}}
<input name="_method" type="hidden" value="PUT">
<label for="category_id" id="category_id">Select Category</label>
<select class="form-control" id="category_id" style="height:auto;" name="category_id">
#foreach($categories as $category)
<hr class="custom-hr-heading"/>
<option value="{{$category->id}}" {{($category->id == $post->category->id)?"selected='selected'":""}}>
{{$category->name}}
</option>
#endforeach
</select>
<label for="title" class="mt-2" name="title" id="title">Your Post Title</label>
<input type="text" class="form-control mb-2" value="{{$post->title}}" name="title" id="title">
<textarea class="form-control" name="body">{{$post->body}}</textarea>
<label for="tags" id="tags" name="tags">Select Tags..</label>
<select class="selectpicker mt-3" id="tags[]" name="tags[]" multiple="multiple">
#foreach($tags as$tag)
<option value="{{$tag->id}}">{{$tag->name}}</option>
#endforeach
</select>
<br/>
<button type="submit" class="btn mt-3 btn-success btn-sm">Update</button>
</form>
<script type="text/javascript">
tinymce.init({
selector: 'textarea',
theme: 'modern',
height: 300
});
$('.selectpicker').selectpicker({
style: 'btn-info'
});
</script>
#stop
Controller
public function edit($id)
{
$post = Post::find($id);
$categories = Category::orderBy('name', 'asc')->get();
$tags = Tag::orderBy('name', 'asc')->get();
return view('posts.edit', compact('post', 'categories', 'tags'))
}
I get a themed select box that just says nothing selected. Am I passing the tags collection to the select box correctly?
I'm using Laravel 5.5, PHP 7.2, and Bootstrap 4.
I've tried bootstrap-select via CDN and local files.

You are missing a space
Change:
#foreach($tags as$tag)
To:
#foreach($tags as $tag)

As per Bootstrap 4's documentation, this is a short attribute, not a name-value pair, so I would do it like so (and clean it up a little):
<select class="form-control" id="category_id" style="height:auto;" name="category_id">
<option value="">Choose an Option</option>
#foreach($categories as $category)
<hr class="custom-hr-heading"/>
<option value="{{ $category->id }}" #if($category->id == $post->category->id) selected #endif >
{{ $category->name }}
</option>
#endforeach
</select>

The problem was infact two problems.
Bootstrap 4 (final) support is only available in the latest bootstrap-select beta release here
Also my code was a little out. Here is the final working code.
<select class="selectpicker mt-3 form-control" name="tags[]" multiple>
#foreach($tags as $tag)
<option value="{{$tag->id}}" {{$post->tags->contains($tag->id)?"selected='selected":""}}>{{$tag->name}}</option>
#endforeach
</select>

Related

How to set the multiple default value in laravel livewire

i have a multiple product when i get the default value of that product, but when i get that value in input field the default value doesn't show ?
<x-filament::page>
<form wire:submit.prevent="submit">
<div>
#if (session()->has('message'))
<div class="alert alert-success">
{{ session('message') }}
</div>
#endif
</div>
<select wire:model="user_type">
<option value="">Select User Type.....</option>
<option value="admin">Admin</option>
<option value="distributor">Distributor</option>
<option value="retailer">Retailer</option>
</select><br><br>
<input wire:model="name" type="text" placeholder="Name"><br><br>
<input wire:model="email" type="email" placeholder="Email Address"><br><br>
<input wire:model="password" type="password" placeholder="Password"><br><br>
<div align = "center">Products</div>
** #foreach($product as $val)
<br><br> {{ $val->name }} :
<input type="number" wire:model="default_price" value = "{{$val->default_price}}">
#endforeach<br><br>**
<button type="submit">
Submit
</button>
</form>
</x-filament::page>
Check these screencasts. They are very helpful! https://laravel-livewire.com/screencasts/data-binding
<input type="number" wire:model="default_price" value = "{{$val->default_price}}">
Livewire doesn't use value attribute!
If you want to update Product->default_price, you can use https://laravel-livewire.com/docs/2.x/properties#binding-models or if you want to only output the default_price, then remove wire:model.
Also #foreach($products as $val) $products should be plural,
and $val should be $product, because it is a product variable. Naming is important, if you don't want to confuse yourself and others constantly.

laravel passing parameters to route in view blade

So I'm very new to laravel and I have a filter in my website blade as follows:
goal: the user chooses a city and price from and price to and then clicks search and villas with what selected must be shown on another view! all values from the database!
I've tried to do this:
the route:
Route::get('/searched/{city_id}/{pricefrom}/{priceto}', [WebsiteController::class, 'search'])->name('search.clicked');
the controller:
public function index() {
$cities = DB::table('cities')
->select('*')->distinct()->get();
$users = Villa::with('City','Seller', 'Payment')->get();
$pricefrom = DB::table('villas')
->select('price')
->where('price', '<=', 50000)->distinct()->get();
$priceto = DB::table('villas')
->select('price')
->where('price', '>', 50000)->distinct()->get();
return view('website', compact('users','cities','pricefrom','priceto'));
}
public function search($city_id, $pricefrom, $priceto) {
$city = City::find($city_id);
$price = Villa::find($price);
$citydata = Villa::with('City','Seller', 'Payment')->where('city_id', $city_id)->get();
$lowdata = Villa::with('City','Seller', 'Payment')->where('price', $pricefrom)->get();
$highdata = Villa::with('City','Seller', 'Payment')->where('price', $priceto)->get();
$info = Villa::with('City','Seller', 'Payment')->get();
return view ('searched',compact('citydata','lowdata','highdata','info'))->with('city', $city )->with('price', $price);
}
the website view blade: here I didn't know how exactly I should pass the parameters for the route so I get an error
#foreach ($users as $villa)
<form action="{{ route('search.clicked', $villa->city_id,$villa->pricefrom,$villa->priceto) }}" method="get">
#csrf
<select name="city" class="form-select">
<option value="" id="searchoption"> City </option>
#foreach ($cities as $city)
<option >{{ $city->name }}</option>
#endforeach
</select>
<div class="col-lg-3 p-2">
<select name="pricefrom" class="form-select">
<option value="" id="searchoption"> Price From </option>
#foreach ($pricefrom as $low)
<option >{{ $low->price}}</option>
#endforeach
</select>
</div>
<div class="col-lg-3 p-2">
<select name="priceto" class="form-select">
<option value="" id="searchoption"> Price To </option>
#foreach ($priceto as $high)
<option >{{ $high->price}}</option>
#endforeach
</select>
</div>
<div class="col-lg-3 p-2">
<button type="button" class="btn btn-outline-success">search</button>
</div>
</form>
#endforeach
also Villa model
class Villa extends Model {
use HasFactory;
protected $fillable=[
"id", "title", "description", "price", "state", "status", "city_id", "seller_id", "payment_id",
"created_at", "updated_at"
];
public function City()
{
return $this -> hasOne(City::class,'id','city_id');
}
public function Seller()
{
return $this -> hasOne(Seller::class,'id','seller_id');
}
public function Payment()
{
return $this -> hasOne(Payment::class,'id','payment_id');
}
}
I think I have many errors I should fix And I want some help with my search bar!
I get this error:
Missing required parameters for [Route: search.clicked] [URI: searched/{city_id}/{pricefrom}/{priceto}] [Missing parameters: pricefrom, priceto].
try:
<form action="{{ route('search.clicked', [$villa->city_id,$villa->pricefrom,$villa->priceto]) }}" method="get">
According to route function second parameter should be string or array. String or Array if you're passing only 1 & array if you are passing 2 or more.
function route($name, $parameters = [], $absolute = true)
BLADE FILE:
#foreach ($users as $villa)
<form action="{{ route('search.clicked', $villa->city_id,$villa->pricefrom,$villa->priceto) }}" method="get">
#csrf
<select name="city" class="form-select">
<option value="" id="searchoption"> City </option>
#foreach ($cities as $city)
<option >{{ $city->name }}</option>
#endforeach
</select>
<div class="col-lg-3 p-2">
<select name="pricefrom" class="form-select">
<option value="" id="searchoption"> Price From </option>
#foreach ($pricefrom as $low)
<option >{{ $low->price}}</option>
#endforeach
</select>
</div>
<div class="col-lg-3 p-2">
<select name="priceto" class="form-select">
<option value="" id="searchoption"> Price To </option>
#foreach ($priceto as $high)
<option >{{ $high->price}}</option>
#endforeach
</select>
</div>
<div class="col-lg-3 p-2">
<button type="button" class="btn btn-outline-success">search</button>
</div>
</form>
#endforeach
to
#foreach ($users as $villa)
<form action="{{ route('search.clicked', ['city_id' => $villa->city_id, 'pricfrom' => $villa->pricefrom, 'priceto' =>$villa->priceto]) }}" method="get">
#csrf
<select name="city" class="form-select">
<option value="" id="searchoption"> City </option>
#foreach ($villa->cities as $city)
<option >{{ $city->name }}</option>
#endforeach
</select>
<div class="col-lg-3 p-2">
<select name="pricefrom" class="form-select">
<option value="" id="searchoption"> Price From </option>
#foreach ($villa->pricefrom as $low)
<option >{{ $low->price}}</option>
#endforeach
</select>
</div>
<div class="col-lg-3 p-2">
<select name="priceto" class="form-select">
<option value="" id="searchoption"> Price To </option>
#foreach ($villa->priceto as $high)
<option >{{ $high->price}}</option>
#endforeach
</select>
</div>
<div class="col-lg-3 p-2">
<button type="button" class="btn btn-outline-success">search</button>
</div>
</form>
#endforeach
You need add to route :
<form action="{{ route('search.clicked',$object->first()->city_id,$model->first()->pricefrom,$model->first()->priceto) }}" method="get">

How to handle validation of multiple hidden fields

I have created a form where in many cases some fields are not displayed until user select a certain option that will make the particular field displayed, this is controlled by HTML onchange Event Attribute with functions in script. To this point everything works fine.
Problem:
In the Request class I am implementing some rules for validation , for all displayed fields and for particular none displayed fields if only their options are selected then they should be validated. In my case I have 8 of this none displayed fields are a_text, b_text, c_text, d_text, e_text, f_text,g_text, h_text. If this fields were 2 it would be easy to write an If statement to choose which should be validated and which should not be validated like below:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Request;
class StoreSectionERequest extends FormRequest
public function rules(Request $request)
{
$a = $request->a;
$b = $request->b;
if($a==5 && $b==3){
return [
//for none displayed fields only validate the below
'a_text' =>'required',
'b_text' =>'required',
//..and other displayed fields will be valuated.
];
}elseif(!$a==5 && $b==3){
return [
//for none displayed fields only validate the below
'b_text' =>'required',
//..and other displayed fields will be valuated.
];
}elseif($a==5 && !$b==3){
return [
//for none displayed fields only validate the below
'a_text' =>'required',
//..and other displayed fields will be valuated.
];
}
// in case all none displayed field are not selected only check other fields below
return [
// validaying all none displyed field here]; }}
In my case I have 8 fields which are none displayed, of which I have to handle all cases of fields if it's selected and not, this will lead to 100's or a lot of if...elseif..statements. What is the wright approach to handle this kind of task.
Form
<form method="POST" action="{{ route('......') }}">#csrf
<div class="row">
<div class="col-md-5" id="lackingSkills">
<label for="">Which skills and competencies graduates are lacking? </label>
<select name="a" multiple="multiple" id="skills" class="form-control select2 #error('a')
is-invalid
#enderror" onchange="myFunction()">
<option value="1" #if (old('a')=="1" ) {{ 'selected' }} #endif>Information and communication skills</option>
<option value="2" #if (old('a')=="2" ) {{ 'selected' }} #endif>Interpersonal skill</option>
<option value="3" #if (old('a')=="3" ) {{ 'selected' }} #endif>System management skills</option>
<option value="4" #if (old('a')=="4" ) {{ 'selected' }} #endif>Innovation skills</option>
<option value="5" #if (old('a')=="5" ) {{ 'selected' }} #endif>Others. Specify</option>
</select>
<small class="text-primary">If necessary, choose more than one option.</small>
#error('a') <span class="invalid-feedback" role="alert">{{ $message }}</span> #enderror
</div>
<div class="col-md-6" id="skillReason" {!! $errors->has('a_text') || old('a') == 5 ? '':' style="display: none"' !!} >
<div class="form-floating mb-3">
<textarea rows="2" class="form-control #error('a_text')#enderror" name="e2_10" id="skillReason" placeholder="Type here.."></textarea>
</div>
</div>
<div class="col-md-6">
<select name="b" id="b" class="form-control" onchange="myFunction2()">
<option value="" selected disabled>Select</option>
<option value="1" #if (old('b')=="1" ) {{ 'selected' }} #endif>Most of them match the requirements</option>
<option value="2" #if (old('b')=="2" ) {{ 'selected' }} #endif>Only some match the requirements</option>
<option value="3" #if (old('b')=="3" ) {{ 'selected' }} #endif>Other, specify</option>
</select>
#error('b') <span class="invalid-feedback" role="alert">{{ $message }}</span> #enderror
</div>
<div class="col-md-6 mt-2" {!! $errors->has('e3_5') || old('b') == 3 ? '':' style="display: none"' !!} >
<div class="form-floating mb-3">
<textarea rows="2" class="form-control" id="b_text" name="b_text" placeholder="Type here.."></textarea>
<label for="floatingInput" id="specify">Specify here..</label>
</div>
</div>
<div class="col-md-6">
<select name="c" id="graduatesPreference" class="form-control" onchange="myFunction3()">
<option value="" selected disabled>Select</option>
<option value="1" #if (old('c')=="1" ) {{ 'selected' }} #endif>Yes</option>
<option value="2" #if (old('c')=="2" ) {{ 'selected' }} #endif>No</option>
</select>
#error('c') <span class="invalid-feedback" role="alert">{{ $message }}</span> #enderror
</div>
<div class="col-md-6" id="preferenceReason" {!! $errors->has('c_text') || old('c') == 1 ? '':' style="display: none"' !!}>
<label for="">Provide the reason, why you have a preference for a specific university?</label>
<textarea name="c_text" id="" rows="3" class="form-control" placeholder="Provide the reason here ..."></textarea>
</div>
<div class="col-md-6">
<select name="d" id="qualification" class="form-control #error('d')is-invalid #enderror" onchange="myFunction4()">
<option value="" selected disabled>Select</option>
<option value="1" #if (old('d')=="1" ) {{ 'selected' }} #endif>Bachelor’s degree</option>
<option value="2" #if (old('d')=="2" ) {{ 'selected' }} #endif>Post-graduate</option>
<option value="3" #if (old('d')=="3" ) {{ 'selected' }} #endif>Other, specify</option>
</select>
#error('d') <span class="invalid-feedback" role="alert">{{ $message }}</span> #enderror
</div>
<div class="col-md-12" id="d_text" {!! $errors->has('d_text') || old('d') == 3 ? '':' style="display: none"' !!}>
<label for="">Explain why?</label>
<textarea name="d_text" id="d_text" rows="3" class="form-control" placeholder="Provide the reason here ..."></textarea>
</div>
////.............others fields like e,f,g,h, all have the same functionality like the above ones.
<div class="action-button d-flex justify-content-center bg-white pt-2 pb-2">
<button type="submit" class="btn btn-success">Save</button>
</div>
</div>
</form>
<script>
/// various function for onchange
myFunction()
myFunction2()
myFunction3()
myFunction4()
</script>
My question: what is the wright approach to handle the above scenario without writing 100's of if..elseif statements. Thanks in advance.
In form validation u have rules like required with or without, u can see more here
Little bit lower on the docs u can see Conditionally Adding Rules
So basically u will be doing same validation but without too much mess in your code.

Laravel Livewire Select2 Multiple sellect issue

Product variation Color first time is disable after enable can select color.
without wire:ignore after select color its disappear from select option.
If I use wire:ignore
{{ $colors_active== 0 ?'disabled':'' }}
disable is not removed, it's still disabled.
product.blade.php
<div class="row g-3 align-center">
<div class="col-lg-3">
<div class="form-group">
<input class="form-control" type="text" value="Colors" readonly>
</div>
</div>
<div class="col-lg-8">
<div class="form-group">
<select class="form-control color-select2" multiple style="width: 100%" {{ $colors_active== 0 ?'disabled':'' }} >
#foreach (App\Models\Admin\Color::orderBy('name', 'asc')->get() as $key => $color)
<option value="{{$color->code}}">
{{$color->name}}
</option>
#endforeach
</select>
</div>
</div>
<div class="col-lg-1">
<div class="form-group">
<div class="form-control-wrap">
<label class="c-switch c-switch-pill c-switch-opposite-success">
<input wire:model="colors_active" class="c-switch-input" type="checkbox" value="1" ><span class="c-switch-slider"></span>
</label>
</div>
</div>
</div>
</div>
Product.php Component
{
public $colors_active;
public $choice_attributes = [];
public $colors = [];
public function mount(){
}
public function render()
{
return view('livewire.admin.product.product')->layout('admin.layouts.master');
}
}
Livewire will ignore any changes to anything marked with wire:ignore, so naturally it will not re-render anything when its ignored.
You can solve this by using Apline.js, and entangle the $colors_active property to an attribute in Alpine.js. Entangle means that when Livewire updates the variable in its backend, Alpine updates its variable too - and vice-versa (Alpine.js updates Livewire when the variable is changed). Basically, its kept in sync between the two.
Then, you can make Alpine.js dynamically bind the disabled property of your select-element based on that variable.
<div x-data="{ 'colorsActive': #entangle('colors_active') }">
<select
class="form-control color-select2"
multiple
style="width: 100%"
wire:ignore
x-bind:disabled="colorsActive == 0"
>
#foreach (App\Models\Admin\Color::orderBy('name', 'asc')->get() as $key => $color)
<option value="{{ $color->code }}">
{{ $color->name }}
</option>
#endforeach
</select>
</div>
This is the way I use to approach this kind of solutions with Livewire, without Alpine because unfortunately I haven't learn it.
In the blade component:
<div class="col d-flex display-inline-block">
<label>Device</label>
<select {{ $customer ? '' : 'disabled' }} wire:model="selectedItem" class="form-control contact_devices_multiple" multiple="multiple" data-placeholder="Select" style="width: 100%;">
#foreach($devices as $device)
<option value="{{ $device->id }}">{{ $device->alias }}</option>
#endforeach
</select>
</div>
<script>
window.loadContactDeviceSelect2 = () => {
$('.contact_devices_multiple').select2().on('change',function () {
livewire.emitTo('contact-component','selectedItemChange',$(this).val());
});
}
loadContactDeviceSelect2();
window.livewire.on('loadContactDeviceSelect2',()=>{
loadContactDeviceSelect2();
});
</script>
in component
public $customer = null;
public $selectedItem = [];
public function hydrate()
{
$this->emit('loadContactDeviceSelect2');
}
public $listeners = [
'selectedItemChange',
];
public function selectedItemChange($value)
{
dd($value);
}

How can I fetch record drom database in edit view In Laravel?

In my edit view I have code like this
<div class="form-group">
<label class="col-md-12">Last Name</label>
<div class="col-md-12">
<input type="text" placeholder="Enter Last Name" name="lastName" class="form-control form-control-line" value="{{$profile->personal_detail['last_name']}}" required>
</div>
</div>
<div class="form-group">
<label class="col-md-12">Department</label>
<div class="col-md-12">
<select class="custom-select form-control col-md-11" id="department" name="department">{{ $profile->personal_profile['department'] }}
#foreach($listDepartment as $departmentList){
<option value='{{$departmentList->nameOfDepartment}}'>{{$departmentList->nameOfDepartment}}</option>
}
#endforeach
</select>
</div>
</div>
In edit view my last name field it gives me last name from database, in department it display me drop down of department but I want that inserted name of department in that field.
how can i get it??
I have other drop down like this
<div class="row">
<label class="col-md-6"><b> Mode </b></label>
<div class="col-md-6">
<select class="custom-select form-control col-md-12" name="mode" id="mode" required>
<option value=""> --- Select Interciew Mode --- </option>
<option value="telephonic">Telephonic</option>
<option value="facetoface">Face 2 face</option>
<option value="skype">Skype</option>
</select>
</div>
</div><hr>
This is my controller
public function candidateDetail($id)
{
$empDetails = User::all();
$candidateDetail = EmployeeHire::find($id);
$interview = [
'' => '--- Select Interciew Mode ---',
'telephonic' => 'Telephonic',
'facetoface' => 'Face 2 face',
'skype' => 'Skype'
];
return view('pages.candidatedetails', compact('id', 'candidateDetail', 'empDetails', 'interview'));
}
You can check in your foreach if the value of nameOfDepartment match the one from your user.
<div class="form-group">
<label class="col-md-12">Department</label>
<div class="col-md-12">
<select class="custom-select form-control col-md-11" id="department" name="department">
#foreach($listDepartment as $departmentList)
#if ($profile->personal_profile['department'] == $departmentList->nameOfDepartment)
<option value="{{$departmentList->nameOfDepartment}}" selected="selected">{{$departmentList->nameOfDepartment}}</option>
#else
<option value="{{$departmentList->nameOfDepartment}}">{{$departmentList->nameOfDepartment}}</option>
#endif
#endforeach
</select>
</div>
</div>
For your second select field, create an array with all possible values in your controller.
$interview = [
'' => '--- Select Interciew Mode ---',
'telephonic' => 'Telephonic',
'facetoface' => 'Face 2 face',
'skype' => 'Skype'
];
Then you can do the same as your previous select :
<select class="custom-select form-control col-md-12" name="mode" id="mode" required>
#foreach($interview as $key => $name)
#if ($profile->personal_profile['interview'] == $key)
<option value="{{ $key }}" selected="selected">{{ $name }}</option>
#else
<option value="{{ $key }}">{{ $name }}</option>
#endif
#endforeach
</select>

Categories