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">
when add next select, you lose the data of the first select of the municipalities.
Livewire controller SelectUsuario.php
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use Illuminate\Support\Facades\Http;
class SelectUsuario extends Component
{
public $estados;
public $estado;
public $estadoSigla;
public $municipios;
public $selects = [];
public $i = 0;
public function add($i)
{
$i = $i + 1;
$this->i = $i;
array_push($this->selects, $i);
}
public function remove($i)
{
unset($this->selects[$i]);
}
public function mount()
{
$this->estados = Http::get(
url("https://servicodados.ibge.gov.br/api/v1/localidades/estados"),
['orderBy' => 'nome']
)->json();
}
public function updatedEstadoSigla()
{
$this->getMunicipios();
}
public function getMunicipios()
{
if ($this->estadoSigla != '') {
foreach ($this->estadoSigla as $estado) {
$this->municipios = json_decode(
Http::get(
url("https://servicodados.ibge.gov.br/api/v1/localidades/estados/{$estado}/municipios")
)->body(),
true
);
}
}
}
public function render()
{
return view('livewire.select-usuario');
}
}
Livewire component select-usuario.blade.php
<div class="form-group row">
<div class="col-3"><label>Viagem</label></div>
<div class="col-3"><label>Seção</label></div>
<div class="col-4"><label>Funcionário</label></div>
<div class="col-2"><label>Ação</label></div>
<div class="col-3">
<select class="form-control" data-item_id="0">
<option value="R">Responsável</option>
</select>
</div>
<div class="col-3">
<select wire:model="estadoSigla.0" class="form-control" id="estado.0" name="estado.0">
<option value="">selecione estado...</option>
#foreach ($this->estados as $estado)
<option value="{{ $estado['sigla'] }}">{{ $estado['nome'] }}</option>
#endforeach
</select>
</div>
<div class="col-4">
#if ($this->estadoSigla)
<select class="form-control" name="municipio.0" id="municipio.0">
<option value="" selected>selecione município...</option>
#foreach ($this->municipios as $municipio)
<option value="{{ $municipio['id'] }}">{{ $municipio['nome'] }}</option>
#endforeach
</select>
#endif
</div>
<div class="col-2">
<button class="btn btn-info mb-2" wire:click.prevent="add({{ $i }})">adicionar</button>
</div>
{{-- Add Form --}}
#foreach ($selects as $key => $value)
<div class="col-3">
<select name="item_name[]" class="form-control" data-item_id="{{$value}}">
<option value="I">Ida</option>
<option value="V">Volta</option>
<option value="O">Ida e Volta</option>
<option value="R">Responsável</option>
</select>
</div>
<div class="col-3">
<select wire:model="estadoSigla.{{ $value }}" class="form-control" name="estado.{{ $value }}" id="estado.{{ $value }}">
<option value="">selecione estado...</option>
#foreach ($this->estados as $estado)
<option value="{{ $estado['sigla'] }}">{{ $estado['nome'] }}</option>
#endforeach
</select>
</div>
<div class="col-4">
#if ($estadoSigla)
<select class="form-control" name="municipio.{{ $value }}" id="municipio.{{ $value }}">
<option value="" selected>selecione município...</option>
#foreach ($this->municipios as $municipio)
<option value="{{ $municipio['id'] }}">{{ $municipio['nome'] }}</option>
#endforeach
</select>
#endif
</div>
<div class="col-2">
<button class="btn btn-dark mb-2" wire:click.prevent="remove({{ $key }})">remover</button>
</div>
#endforeach
</div>
try adding wire:key directive to the looped select elements while livewire need to keep tracking all the values of them.
<select wire:model="estadoSigla.{{ $value }}" class="form-control" id="estado.{{ $value }}" wire:key="estado-select-{{ $key }}"> // or $value, the unique identifier for its
also, try adding wire:ignore.self to the root div of the select elements
I am trying to show roles which is related to user but unfortunately userRoles are not showing related to user in selection option, please help me how can I match that thanks.
Note :- I am using spaite laravel permission docs
controller
public function edit(User $user)
{
$data = [
'isEdit' => true,
'user' => $user,
'roles' => Role::where('guard_name', '=', 'web')->select(['id', 'name'])->get(),
'userRole' => $user->getRoleNames(),
// i am getting userRole in array related to user
// ['employe']
];
// return $data['userRole'];
return view('cms.user_management.add-user', $data);
}
html view
<div class="col-md-6">
<div class="form-group">
<label>Role <span class="text-danger">*</span></label>
<select class="form-control" name="roles[]">
<option selected="selected" disabled >please
select</option>
#foreach ($roles as $item)
<option value="{{ $item->name }}"{{ $userRole ==
$item->name ? ' selected' : '' }}>{{ $item->name }}</option>
#endforeach
</select>
</div>
<span class="text-danger">{{ $errors->first('roles') ?? null }}
</span>
</div>
Try the following changes in your HTML
If $userRole is array than check if $item->name exists in array, using in_array.
'userRole' => $user->getRoleNames()->toArray(),
html view
{{ in_array($item->name, $userRole) ? 'selected' : '' }}
<div class="col-md-6">
<div class="form-group">
<label>Role<span class="text-danger">*</span></label>
<select class="form-control" name="roles[]">
<option selected="selected" disabled>please select</option>
#foreach ($roles as $item)
<option value="{{ $item->name }}"{{ in_array($item->name,$userRole) ? 'selected' : '' }}>{{ $item->name }}</option>
#endforeach
</select>
</div>
<span class="text-danger">{{ $errors->first('roles') ?? null }}</span>
</div>
you can use this to get the roles asssociated with current user or
Auth::user()->roles->pluck('name');
for any specific user roles.
User::find($id)->roles->pluck('name')
I have two dropdowns one for asc desc and one with the field name. When I change page I am able to keep the order and order_by parameter and the page number. When I change one of the dropdown a postback happens In that case I lose the page number. How can I fix this problem.
Here is the url I want
home?orderby=created_at&order=desc&page=2
Here is the url I have in the case of a dropdown change
home?orderby=created_at&order=desc
Here is my front end code
<form action="{{ route('home') }}" method="GET">
<div class="row">
<div class="col-2">
<label for="nom">Trier par :</label>
</div>
<div class="col-tier form-group">
<select class="form-control" name="orderby" id="orderby" onchange="this.form.submit()">
<option value="nom" {{ Request()->orderby == 'nom' ? ' selected' : '' }}>Nom</option>
<option value="created_at" {{ Request()->orderby == 'created_at' ? ' selected' : '' }}>Date de création</option>
<option value="updated_at" {{ Request()->orderby == 'updated_at' ? ' selected' : '' }}>Date de modification</option>
</select>
</div>
<div class="col-tier form-group ">
<select class="form-control" name="order" id="order" onchange="this.form.submit()">
<option value="desc" {{ Request()->order == 'desc' ? ' selected' : '' }}>Desc</option>
<option value="asc" {{ Request()->order == 'asc' ? ' selected' : '' }}>Asc</option>
</select>
</div>
</div>
</form>
<div id="pagination" class="d-flex justify-content-center">
{{ $grilles->appends(request()->except('page'))->links() }}
</div>
Here is the code of the controlleur
public function index(Request $request)
{
$user = Auth::user();
$sort = "ASC";
if($request->get('order')==="desc")
{
$sort="DESC";
}
if ($request->get('orderby')==="created_at") {
$grilles = Grille::orderBy('created_at', $sort)->paginate(15)->appends(request()->query());
} else if ($request->get('orderby')==="updated_at") {
$grilles =Grille::orderBy('updated_at', $sort)->paginate(15)->appends(request()->query());
}
else{
$grilles =Grille::orderBy('nom', $sort)->paginate(15)->appends(request()->query());
}
return view('home', compact('grilles'));
}
<div id="pagination" class="d-flex justify-content-center">
{{ $grilles->appends(request()->except('page'))->links() }}
</div>
On the Edit view I have a Select field and I want that select field to have the saved value for a given Model to be selected.
mediaController.php
public function edit($id)
{
//
$media = Media::find($id);
$categories = Category::lists('category', 'id');
return view('medias.edit-media')->with('media', $media)->with('categories', $categories);
}
edit.blade.php
<div class="form-group">
{!! Form::select('categories', $categories, $media->category ) !!}
</div>
On the index view (i.e the first Media as a Category of Video)
On the edit view (the first Media doesn't have the Category 'Video' selected)
even if I change my edit.blade.php to this: ...
<div class="form-group">
<label>Category of Upload
<select name="category" id="category" class="form-control input-sm">
#foreach($categories as $category)
<option value="{{ $category }}" {{ Input::old($media->category) == $category ? 'selected' : '' }}>{{ $category }}</option>
#endforeach
</select>
</label>
</div>
I still have the same result (the right Category is not selected)
<div class="form-group"><label>Category of Upload <select name="category" id="category" class="form-control input-sm"> #foreach($categories as $category) <option value="{{ $category->id }}" {{ $media->categories == $category->id ? 'selected' : '' }}>{{ $category }}</option>#endforeach </select> </label></div>