Laravel, Search by month, but I can't find anything - laravel

I'm doing a search a month, but I can't find anything. Start is a column of type date, 2020-07-23.
Controller:
public function cityName(Request $request, City $city)
{
$month = $request->month;
$status = $request->status;
if (!empty($month)) {
$chamado = Chamados::where('cite_id', $city->id)
->whereMonth('start', $month)
->when($status, function ($query, $status) {
return $query->where('status', $status);
})->get();
} else {
$chamado = Chamados::where('cite_id', $city->id)->get();
}
$total = Chamados::where('cite_id', $city->id)->value(DB::raw('SUM(total)'));
return view('admin.reports.city.city_name', compact('city', 'chamado', 'total', 'month'));
}
My form:
<form class="form-inline mb-3" action="{{ route('dashboard.report.city.name', $city->id) }}" id="formSearch" method="GET">
<input type="month" class="form-control form-control-sm mr-md-2" name="month" id="month" value="{{ isset($month) ? $month : '' }}">
<button type="button" name="filter" id="filter" class="btn btn-info btn-sm mr-2 mb-2">
<i class="fad fa-filter"></i> Filter
</button>
</form>
without search
with search

The whereMonth() method may be used to compare a column's value against a specific month of a year:
$chamado = Chamados::whereMonth('start', $month)

Related

Append sort route with search results in Laravel

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

production.ERROR: Undefined variable: id Laravel blade

In my Laravel-5.8 I have this code in the controller:
public function appraisal(Request $request)
{
try {
$userCompany = Auth::user()->company_id;
$userId = Auth::user()->id;
$company = OrgCompany::where('id', $userCompany)->first();
$identities = Identity::where('company_id', $userCompany)->pluck('appraisal_name','id');
$goals = AppraisalGoal::where('employee_id', $userId)
->where(function ($query) {
$query->where('is_approved', 3)->orWhere('is_visible', 0);
})
->whereNull('deleted_at')
->orderBy('goal_type_id');
$method = $request->method();
if ($request->isMethod('post')) {
$id = $request->input('identity_id');
if ($request->has('search')) {
// select search
if ($request->input('identity_id')) {
$goals->where('identity_id',$request->input('identity_id'));
}
$goals = $goals->get();
return view('appraisal-default',['goals' => $goals, 'identities' => $identities]);
} elseif ($request->has('viewIdentity')) {
// select goal identity
if ($request->input('identity_id')) {
return view('performance_dashboard', $id);
}
}
} else {
//select current year
$goals = $goals->get();
return view('appraisal-default',['goals' => $goals, 'identities' => $identities]);
}
} catch (Exception $exception) {
Log::error($exception);
Session::flash('error', 'Action failed! Please try again');
return back();
}
}
view blade: appraisal-default
<div class="row" style="margin-bottom: 10px">
<label class="control-label"> Performance Period:<span style="color:red;">*</span></label>
<div class="col-sm-8">
<select id="identity" name="identity_id" class="form-control">
<option value="">--- Select Performance Period ---</option>
#foreach ($identities as $ids => $name)
<option value="{{ $ids }}" {{ request( 'identity_id')==$ids ? 'selected' : ''}}>{{ $name }}</option>
#endforeach
</select>
</div>
<div class="col-xs-4">
<button type="submit" class="btn btn-primary btn-sm" name="search">Search</button>
<form action="{{ route('performance_dashboard', $id->id) }}" method="get" target="_blank" class="form-horizontal" enctype="multipart/form-data">
{{csrf_field()}}
<button type="submit" class="btn btn-secondary btn-sm" name="viewIdentity"><i class="fas fa-file-pdf"></i> View Identity</button>
</form>
</div>
</div>
In the view, I have two buttons with names: search and viewIdentity
When the
<select id="identity" name="identity_id" class="form-control">
is selected.
If search button is submitted, it displays the result on the same page. This is working.
However, where I'm having problem is when viewIdentity button is submitted. At this point it suppose to take the id of the dropdown as the parameter in:
<form action="{{ route('performance_dashboard', $id->id) }}" method="get" target="_blank" class="form-horizontal" enctype="multipart/form-data">
{{csrf_field()}}
<button type="submit" class="btn btn-secondary btn-sm" name="viewIdentity"><i class="fas fa-file-pdf"></i> View Identity</button>
</form>
and display the result in another page: performance_dashboard
I got this error in the view:
production.ERROR: Undefined variable: id
It points to this line in the view:
<form action="{{ route('performance_dashboard', $id->id) }}" method="get" target="_blank" class="form-horizontal" enctype="multipart/form-data">
How do I get it resolved?
Thanks

why do i get this problem when i want to filter project

I want to add the translate feature to my website. but I got this problem
Missing required parameters for [Route: filterdata] [URI: {locale}/project/{filter}]
this is the app web route:
Route::get('/', function () {
return redirect(app()->getLocale());
});
Route::get('/project', function () {
return redirect(app()->getLocale());
});
Route::group([
'prefix' => '{locale}',
'where' => ['locale' => '[a-zA-Z]{2}'],
'middleware' => 'setlocale',
], function(){
Route::get('/', function(){
return view('pages.home');
})->name('home');
Route::get('/project/{filter}', 'ProjectController#filterProject')->name('filterdata');
});
this is the blade project
<a class="btn btn-default" href="{{ url(app()->getLocale().'/project/Branding') }}" role="button">Branding</a>
this is the controller:
public function filterProject($locale, $filter){
$locale = $locale;
$filter = str_replace('-',' ',$filter);
$url = Lang::get('proyek.project');
$url2 = json_encode($url);
$data = json_decode($url2, true);
$data = array_filter($data);
if(collect($data)->where('tag1',"{$filter}")->all() == true){
$project = collect($data)->where('tag1',"{$filter}")->all();
}elseif(collect($data)->where('tag2',"{$filter}")->all() == true){
$project = collect($data)->where('tag2',"{$filter}")->all();
}elseif(collect($data)->where('tag3',"{$filter}")->all() == true){
$project = collect($data)->where('tag3',"{$filter}")->all();
}else{
$project = collect($data)->all();
}
return view ('pages/projects', compact('project','locale','filter'));
}
and this is the buttons I use for language switch:
<div class="form-check d-flex align-items-center">
<input type="radio" class="form-check-input form-control" name="language" id="languageen" value="{{ route(\Illuminate\Support\Facades\Route::currentRouteName(), 'en') }}" onchange="location = this.value;" #if(app()->getLocale() == 'en') checked #endif>
<label class="form-check-label control-label" for="languageen">
EN
</label>
</div>
<div class="form-check d-flex align-items-center">
<input type="radio" class="form-check-input form-control" name="language" id="languageid" value="{{ route(\Illuminate\Support\Facades\Route::currentRouteName(), 'id') }}" onchange="location = this.value;" #if(app()->getLocale() == 'id') checked #endif>
<label class="form-check-label control-label" for="languageid">
ID
</label>
</div>
Seems like you never passed $filter variable to your route, on the button element:
<a class="btn btn-default" href="{{ url(app()->getLocale().'/project/Branding') }}" role="button">Branding</a>
As you can see, you're only passing $locale parameter. In order for this to work, you pass your $filter variable as well
<a class="btn btn-default" href="{{ url(app()->getLocale().'/project/Branding/' . $filter) }}" role="button">Branding</a>
If you don't need $filter every time when you're calling this route, you can make it optional, with the ? operator:
Route::get('/project/{filter?}', 'ProjectController#filterProject')->name('filterdata');
zlatan
"Branding" is a filter
<a class="btn btn-default" href="{{ url(app()->getLocale().'/project/Branding') }}" role="button">Branding</a>

Laravel 5 simple search box using GET method

I want to search code for enter an admin.
web.php
Route::get('/document', 'DocumentController#document')->name('document');
DocumentController.php
public function document()
{
$keyword = request('code');
$documents = Document::document($keyword)->latest()->get();
return view('Home.content.documents', compact('documents'));
}
Document.php
public function scopeDocument($query, $keywords)
{
$keywords = explode(' ',$keywords);
foreach ($keywords as $keyword) {
$query->where('code' , 'LIKE' , '%' . $keyword . '%');
}
return $query;
}
documents.blade,php
<form action="{{ route('document') }}" method="get">
<div class="form-group">
<label for="code">Code</label>
<input type="text" class="form-control col-sm-4" id="code" name="code">
</div>
<button type="submit" class="btn btn-primary">Search</button>
</form>
<div class="text-center">
#foreach($documents as $document)
<h1 class="m-3">{{ $document->first_name }} {{ $document->last_name }}</h1>
<img src="images/documents/{{ $document->image }}" class="img-fluid">
#endforeach
</div>
Why this code is not working?

I got this error "Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type

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');
}

Resources