I want to append my search result /search?allsearch= and sort url /search?sort= together but I can't find the solution yet.
Here is my code:
<form class="form-inline my-2 my-lg-0 rounded left-addon-search inner-addon" action="/search" method="GET">
<i class="fas fa-search"></i>
<input type="text" name="allsearch" class="search-field rounded" placeholder="Search" aria-label="Search" aria-describedby="search-addon" />
</form>
<select id="sort" name="sort">
<option value="">Relevance</option>
<option value="product_price_low_high" #if(isset($_GET['sort']) && $_GET['sort']=="product_price_low_high") selected="" #endif>Price: Low to High</option>
<option value="product_price_high_low" #if(isset($_GET['sort']) && $_GET['sort']=="product_price_high_low") selected="" #endif>Price: High to Low</option>
<option value="product_latest" #if(isset($_GET['sort']) && $_GET['sort']=="product_latest") selected="" #endif>Latest Arrivals</option>
</select>
My Controller:
$search = $request->allsearch;
$product = DB::table('brands')
->join('products', 'brands.id', '=', 'products.brandid')
->where('productname','like','%'.$search.'%')
->OrWhere('name','like','%'.$search.'%');
// sorting product
if (isset($_GET['sort']) && !empty($_GET['sort'])) {
if ($_GET['sort'] == "product_price_low_high") {
$product->orderBy('productprice', 'asc');
} elseif ($_GET['sort'] == "product_price_high_low") {
$product->orderBy('productprice', 'desc');
} elseif($_GET['sort'] == "product_latest") {
$product->orderBy('id', 'desc');
}
}
$product = $product->get();
My route:
Route::get('/search','ProductController#search')->name('allsearch', 'sort');
Independently, the /search?allsearch= and the /search?sort= will work. But if I try to search for something, then sort the results, it clears out the search request.
Any idea how to make this works?
you have to set the request value to the form so that you can work with both of them. you can use hidden input for the missing value in each form
the search form
<form class="form-inline my-2 my-lg-0 rounded left-addon-search inner-addon" action="{{ route('search') }}" method="GET">
<i class="fas fa-search"></i>
<input type="text" name="allsearch" value="{{ request()->allsearch }}" class="search-field rounded" placeholder="Search" aria-label="Search" aria-describedby="search-addon" />
<input type="hidden" name="sort" value="{{ request()->sort }}" />
</form>
the sort form
<form class="form-inline my-2 my-lg-0 rounded left-addon-search inner-addon" action="{{ route('search') }}" method="GET">
<select id="sort" name="sort">
<option value="">Relevance</option>
<option value="product_price_low_high" #if (request()->sort == "product_price_low_high") selected #endif>Price: Low to High</option>
<option value="product_price_high_low" #if (request()->sort == "product_price_high_low") selected #endif>Price: High to Low</option>
<option value="product_latest" #if (request()->sort == "product_latest") selected #endif>Latest Arrivals</option>
</select>
<input type="hidden" name="allsearch" value="{{ request()->allsearch }}" />
</form>
why your route has two names?? route shuold have a single unique name
Route::get('search', 'ProductController#search')->name('search');
and in controller
use Illuminate\Http\Request;
public function search(Request $request)
{
$search = $request->allsearch;
$product = DB::table('brands')
->join('products', 'brands.id', '=', 'products.brandid')
->where('productname', 'like', '%'.$search.'%')
->orWhere('name', 'like', '%'.$search.'%');
if ($request->sort == "product_price_low_high") {
$product->orderBy('productprice', 'asc');
} elseif ($request->sort == "product_price_high_low") {
$product->orderBy('productprice', 'desc');
} elseif ($request->sort == "product_latest") {
$product->orderBy('id', 'desc');
}
$product = $product->get();
return response/view
}
you are using laravel, so try to code as the laravel way
Related
I am trying to show query results without reloading in laravel
This is the form in which I get the category and country
<form class="new_is" id="lets_search" action="{{route('advanced-search.show','searchInfluencer')}} method="GET">
<div class="row">
<div class="col-md-6">
<label>Category</label>
<select name="filter_category" id="filter_category" class="influencer-category-picker form-control form-select" >
<option value="">Click to select the category</option>
#foreach($Categories as $Category)
<option id="category" name="{{$Category->id}}" value="{{$Category->id}}">{{$Category->name}}</option>
#endforeach
</select>
</div>
<div class="col-md-6">
<label>Location</label>
<select name="filter_country" id="filter_country" class="influencer-category-picker form-control form-select">
<option value="" >Click to select the Country</option>
#foreach($Countries as $Country)
<option id="country" value="{{$Country->id}}">{{$Country->name}}</option>
#endforeach
</select>
</div>
<div id="advanced-search" class="col-md-12" style="margin-top: 20px">
<p>
<button type="button" name="filter" id="filter" class="btn btn-lg btn-primary track-event">Search</button>
</p>
</div>
</div>
</form>
This is the controller including the query and returning the result and everything works well but on another page
public function searchInfluencer(Request $request)
{
$category = $request->get('category');
$country = $request->get('country');
if(empty($category) && !empty($country)){
$influencers =Influencer::where('country_id', $country)->get();
return response()->json($influencers);
}
elseif (!empty($category) && empty($country)){
$influencers =Influencer::where('category_id', $category)->get();
return response()->json($influencers);
}
elseif (!empty($category) && !empty($country)){
$influencers =Influencer::where('category_id', $category)->where('country_id', $country)->get();
return response()->json($influencers);
}
Here is the index function:
public function index(){
return view('businesses.advanced-search-business', [
'Genders' => Gender::all(),
'Countries' => Country::all(),
'Categories' => Category::all(),
]);
}
The issue is that on clicking the search button, I want to show the results on the same page without reloading. Thank you in advance for your help
In my controller, I have my create record method, but I want to edit existing records, but only update the fields that are filled out. I try to only fill out one or two fields on the edit property file, but no matter what field I fill out, it returns the same error:
Attempt to assign property "property_title" on null
Update method in my controller:
public function update(Request $request, $id)
{
// Find the record
$prop = Property::find($id);
if ($request->hasFile('prop_img')) {
$file = $request->file('prop_img');
$filenameWithExtension = $file->getClientOriginalName();
$Extension = $file->getClientOriginalExtension();
$filenameOnly = pathinfo($filenameWithExtension, PATHINFO_FILENAME);
$filename = $filenameOnly . time() . '.' . $Extension;
$file->move('property_images', $filename);
$prop->property_image = $filename;
}
$prop->property_title = $request->input('prop_title');
$prop->property_description = $request->input('prop_desc');
$prop->bedrooms = $request->input('prop_beds');
$prop->bathrooms = $request->input('prop_baths');
$prop->square_feet = $request->input('prop_ft');
$prop->finished_basement = $request->input('prop_basement');
$prop->prop_tax = $request->input('prop_tax');
$prop->heat_type = $request->input('prop_heat');
$prop->water_heater = $request->input('prop_waterheater');
$prop->year_built = $request->input('prop_year');
$prop->save();
return view('admin.properties');
}
Routes:
Route::group(['prefix' => 'admin'], function() {
Route::get('/', function() {
return view('admin.dashboard');
})->name('admin')->middleware('auth');
Route::get('/properties', [PropertiesController::class, 'index'])->name('all-properties')->middleware('auth');
Route::get('/properties/create', [PropertiesController::class, 'create'])->middleware('auth');
Route::post('/properties/store-property', [PropertiesController::class, 'store'])->name('admin.store_properties')->middleware('auth');
Route::get('/properties/delete/{id}', [PropertiesController::class, 'destroy'])->middleware('auth');
// Edit property
Route::get('/properties/edit/{id}', [PropertiesController::class, 'edit'])->name('admin.edit')->middleware('auth');
Route::post('/properties/update/{id}', [PropertiesController::class, 'update'])->middleware('auth');
});
Edit properties blade file:
#extends( 'layouts.admin' )
#section( 'content' )
<h1 class="admin-header">Edit Listing</h1>
#if($errors->any())
<h4>{{$errors->first()}}</h4>
#endif
<form method="POST" action="/admin/properties/update/{id}" class="add_edit_property_form" enctype="multipart/form-data">
#csrf
<div>
<label for="prop_title">Property Title</label>
<input type="text" name="prop_title" id="prop_title" />
</div>
<div>
<label for="prop_desciption">Property Description</label>
<textarea name="prop_desc" id="prop_desc"></textarea>
</div>
<div>
<label for="prop_img">Property Image</label>
<input type="file" name="prop_img" id="prop_img" />
</div>
<div>
<label for="prop_beds">Number of Bedrooms</label>
<input type="number" name="prop_beds" id="prop_beds" steps="1" min="1" />
</div>
<div>
<label for="prop_baths">Number of Bathrooms</label>
<input type="number" name="prop_baths" id="prop_baths" />
</div>
<div>
<label for="prop_ft">Sqaure Feet</label>
<input type="number" name="prop_ft" id="prop_ft" />
</div>
<div>
<label for="props_basement">Finished Basement?</label>
<select name="prop_basement" id="prop_basement">
<option value="" selected disabled>Select an option</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</div>
<div>
<label for="prop_tax">Property Tax</label>
<input type="number" name="prop_tax" id="prop_tax" />
</div>
<div>
<label for="props_heat">Heat Type</label>
<select name="prop_heat" id="prop_heat">
<option value="" selected disabled>Select an option</option>
<option value="gas">Gas</option>
<option value="oil">Oil</option>
<option value="electric">Electric</option>
</select>
</div>
<div>
<label for="props_waterheater">Finished Basement?</label>
<select name="prop_waterheater" id="prop_waterheater">
<option value="" selected disabled>Select an option</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</div>
<div>
<label for="prop_year">Year Built</label>
<input type="number" name="prop_year" id="prop_year" />
</div>
<button type="submit">Add New Listing</button>
</form>
#endsection
Edit method code:
public function edit($id)
{
return view('admin.edit_property');
}
Results of var_dump
var_dump($id):
string(5) "{$id}"
var_dump($request::all()):
array(8) { ["_token"]=> string(40) "9QOxw20xoy1mEDD6BTWZEJtMpgl3rC16ACejvtcU" ["prop_title"]=> string(4) "Test" ["prop_desc"]=> NULL ["prop_beds"]=> NULL ["prop_baths"]=> NULL ["prop_ft"]=> NULL ["prop_tax"]=> NULL ["prop_year"]=> NULL }
$prop = Property::find($id);
var_dump($prop):
NULL
this error means that this line
$prop = Property::find($id);
returns null, almost because a null value passed to the $id variable
due to the missing $ sign at the action of the edit form, also the variables at the blade should be with double curly braces
So
1- you need to change this line
<form method="POST" action="/admin/properties/update/{id}" class="add_edit_property_form" enctype="multipart/form-data">
to this and it should work with you
<form method="POST" action="/admin/properties/update/{{$id}}" class="add_edit_property_form" enctype="multipart/form-data">
i just added $ sign and in double curly-braces {{$id}}
2- you need to update your edit method, you need to pass the $id parameter to the view
so, you need to update this method
public function edit($id)
{
return view('admin.edit_property');
}
to
public function edit($id)
{
return view('admin.edit_property')->with('id',$id);
}
or to
public function edit($id)
{
return view('admin.edit_property')->with(compact('id'));
}
I am trying to apply filters to my products
This is my database
I'm trying to filter by gender, if it is a kid or not, price range and size
My form:
<form method="GET" action="{{route('products.all')}}">
<div class="filters">
<select class="form-control search" name="gender">
<option value="" selected disabled hidden>Gender...</option>
<option value="M">Man</option>
<option value="W">Woman</option>
</select>
<label>Kids?</label>
<input class="form-control search" type="checkbox" name="kids" value="1">
<div class="filters-all">
Price...
<div class="search">
<input type="text" class="start d-none" name="price-start" />
<input type="text" class="end d-none" name="price-end" />
<input type="text" id="sampleSlider" />
</div>
</div>
<select class="form-control search" name="size">
<option value="" selected disabled hidden>Sizes...</option>
#foreach($sizes as $size)
<option value="{{$size->size}}">{{$size->size}}</option>
#endforeach
</select>
<input type="submit" class="btn btn-secondary"value="Filter"/>
</div>
</form>
My controller with query:
$gender = $request->get('gender');
$child = $request->get('kids');
$size = $request->get('size');
$price_start = $request->input('price-start');
$price_end = $request->input('price-end');
if(!empty($gender) && !empty($size)&& !empty($price_start) && !empty($price_end)){
Product::whereHas('stocks', function ($query) {
$query->where('size', '=', $size);
})
->whereHas('childs', function ($query){
$query->where('child', '=', $child);
})
->where('gender', '=', $gender)
->whereBetween('price', [$price_start, $price_end])
->inRandomOrder()->paginate(12);
}else{
$products = Product::inRandomOrder()->paginate(12);
}
When submitting the form data, it appears correctly in the get:
But when filtering, the link returns "that the variables are not initialized"
I've been thinking for a while but I have the solution. Maybe the query is wrong?
<div class="row">
<div class="col-md-6">
<h3>Create New Expenses</h3>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form class="form" method="POST" action="{{ route('exp.store') }}" autocomplete="off">
<div class="form-group">
<label>Seller :</label>
<input type="text" name="seller_name" class="form-control" value="{{ old('seller_name',isset($exp) ? $exp->seller_name : '') }}" placeholder="Seller">
</div>
<div class="form-group">
<label>Date :</label>
<input type="date" name="date" class="form-control" value="{{ old('date',isset($exp) ? $exp->date : '') }}">
</div>
<div class="form-group">
<label>Select Type :</label>
<select class="form-control" name="category" value="">
<option value=""> Select Type </option>
<option value="1"{{ isset($exp) ? ($exp->category == 1 ? 'selected' : '') : '' }}> Communication </option>
<option value="2"{{ isset($exp) ? ($exp->category == 2 ? 'selected' : '') : '' }}> Transport </option>
<option value="3"{{ isset($exp) ? ($exp->category == 3 ? 'selected' : '') : '' }}> Tools </option>
<option value="4"{{ isset($exp) ? ($exp->category == 4 ? 'selected' : '') : '' }}> Raw Material </option>
</select>
</div>
<div class="form-group">
<label>Amount(RM) :</label>
<input type="number" name="amount" class="form-control" value="{{ old('amount',isset($exp) ? $exp->amount : '') }}" placeholder="0.00">
</div>
<br>
<button type="submit" class="btn btn-primary btn-sm">Save</button>
<a class="btn btn-danger btn-sm" href="{{ route('exp.index') }}">Cancel</a>
</form>
</div>
</div>
This is my saving data function
public function store(Request $request){
$this->validate($request, [
'seller_name' => 'required|max:50',
'date' => 'required',
'category' => 'required',
'amount' => 'required'
]);
DB::beginTransaction();
try{
$exp = new Exp();
$this->saveData($exp, $request);
DB::commit();
return redirect()->route('exp.index');
} catch (\Exception $ex){
DB::rollback();
return back()->withInput()->withErrors('Fail to save.');
}
}
private function saveData($exp, Request $request){
$exp->seller_name = $request->input('seller_name');
$exp->date = $request->input('date');
$exp->category = $request->input('category');
$exp->amount = $request->input('amount');
$exp->save();
}
This is my Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Exp extends Model
{
protected $table = 'exp';
public $primaryKey = 'exp_id';
}
I'm new using this MVC .... i don't know why cant't saving but all my code look no error.
I try to find it but i find nothing ..
I need some help...
i already provide my view, controller and model
and below is my web.php
Route::get('/exp/create', 'ExpController#create')->name('exp.create');
Route::post('/exp/store', 'ExpController#store')->name('exp.store');
TQ.
Seems like you forgot to add mass assignment fields to your Exp model, hence the fields are not saved in your database. Add all the fields you want to be mass assigned to your model, and it should be working as expected:
protected $fillable = ['field_1', 'field_2', .... 'etc'];
Read more about this on official documentation
When i try to insert data into my table this error occurs
Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type array, string given, called in C:\xampp\htdocs\Portal\vendor\laravel\framew...
view
<form method="post" action="{{ route('notice.store') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="Select Group to Post Notice">Select Group to Post Notice </label>
<select class="bg-white text-danger form-control " name='GroupID[]' multiple>
#foreach ($users as $user)
<option value="{{ $user->GroupID }}">{{ $user->GroupID }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="Enter Notice">Enter Notice</label>
<input class="bg-white text-danger p-2 form-control form-control-sm" type="text" name="Notice" placeholder="Enter Notice">
</div>
<input class="btn btn-danger btn-lg px-5" type="submit" name="submit">
</form>
controller
public function store(Request $request)
{
$member = $request->input('GroupID');
foreach($member as $value) {
$storeInfo = new notice();
$storeInfo->GroupID = $request->input('GroupID');
$storeInfo->Notice = $request->input('Notice');
$storeInfo->save();
}
return redirect('/notice');
}
I would imagine the reason you're getting this error is because of:
$storeInfo->GroupID = $request->input('GroupID');
$request->input('GroupID') will return an array (name='GroupID[]') and not an individual id.
Since you're already looping through the group ids you can instead use the value for the GroupId:
public function store(Request $request)
{
foreach ($request->input('GroupID') as $groupId) {
$storeInfo = new notice();
$storeInfo->GroupID = $groupId; //<--here
$storeInfo->Notice = $request->input('Notice');
$storeInfo->save();
}
return redirect('notice');
}
try changing controller logic
public function store(Request $request)
{
//
$member=$request->input('GroupID');
foreach($member as $value){
$storeInfo = new notice();
$storeInfo->GroupID = $value;
$storeInfo->Notice = $request->input('Notice');
$storeInfo->save();
}
return redirect('/notice');
}