Add the orderBy if the Request::get('xyz') field exist - php

In following pagination query i added the sorting code with OrderBy method but gives an error on first time page reload because there is no sort and order field is set there. how can i condition it set if exist or set null or else.
->select(array(
'to_jobs.rec_id',
'to_jobs.contarct_code',
'to_jobs.job_num',
'to_sites.site_name',
'to_sites.postcode',
'to_sites.site_id'
))
->orderBy(Request::get('sort'), Request::get('order'))
->leftjoin('to_sites', 'to_jobs.fk_site_id', '=', 'to_sites.site_id')
->paginate(10);

If you're using Eloquent, you can use local scope.
For query builder query, you can try to use when():
->when(request()->has('sort'), function ($q) {
return $q->orderBy(request()->sort, request()->order);
})

You can simply use if statement to check sort input and then build your pagination.
Try this.
$query->select(array(
'to_jobs.rec_id',
'to_jobs.contarct_code',
'to_jobs.job_num',
'to_sites.site_name',
'to_sites.postcode',
'to_sites.site_id'
))
->leftjoin('to_sites', 'to_jobs.fk_site_id', '=', 'to_sites.site_id');
if (Request::has('sort'))
{
$query->orderBy(Request::get('sort'), Request::get('order'));
}
$query->paginate(10);
Reference:
Condition based query in laravel

Related

Is it possible to do orderBy() or orderBy() in Laravel?

Is it possible to do orderBy() or orderBy() in Laravel Eloquent? My current query only sorts the item.ItemID upon user clicking sort on the frontend but it won't sort item.Desc when the user clicks sort on the frontend.
I've tried putting these orderBy()s inside of a where() clause using a closure but that didn't work either. Does anyone know of a good way I could rectify this?
$this->model
->join('awards', 'item.ItemID', '=', 'awards.LinkID')
->join('opportunities', 'awards.AwardID', '=', 'branch.AwardID')
->groupBy('item.ItemID', 'item.Desc')
->orderBy('item.ItemID', $clickedDInventoryItemIdFlag ? 'DESC' : 'ASC')
->orderBy('item.Desc', $clickedDescriptionColumnFlag ? 'DESC' : 'ASC')
->select("item.ItemID", "item.Desc", "branch.OppID")
->get();
Ordering in SQL is cumulative, so you'll always be ordering by the first item, then the second. Instead you can manipulate the query based on a condition:
$this->model
->join('awards', 'item.ItemID', '=', 'awards.LinkID')
->join('opportunities', 'awards.AwardID', '=', 'branch.AwardID')
->groupBy('item.ItemID', 'item.Desc')
->when(
$clickedDescriptionColumnFlag, // condition
fn ($q) => $q->orderBy('item.Desc') // true
fn ($q) => $q->orderBy('item.ItemID') // false
)
->select("item.ItemID", "item.Desc", "branch.OppID")
->get();
I have to say though, whenever I see query builder joins happening like this, it's a big flag telling me that you likely don't understand model relationships. (And the fact that you used "Eloquent" in your title, despite there being no such code in the question!) I would strongly suggest looking into how Eloquent works; for all but the heaviest loads the increase in coding efficiency far outweighs the slight decrease in database query efficiency.
Until you call get() method it is all query builder since all chaining methods return self instance. So you can separate chain and use if block when needed:
$someModels = $this->SomeModel
->join('awards', 'item.ItemID', '=', 'awards.LinkID')
->join('opportunities', 'awards.AwardID', '=', 'branch.AwardID')
->groupBy('item.ItemID', 'item.Desc');
if ($condition) {
$someModels->orderBy('item.ItemID', $clickedDInventoryItemIdFlag ? 'DESC' : 'ASC')
} else {
$someModels->orderBy('item.Desc', $clickedDescriptionColumnFlag ? 'DESC' : 'ASC');
}
$someModels
->select("item.ItemID", "item.Desc", "branch.OppID")
->get();

Laravel retreive data from database order by creation date

I am trying to retrieve data orderby creation date desc and get the first one here is my code
$localnews = Articles::whereHas('sous_categories',
function ($query) {
$query->where('id', '15')->order_by('created_at', 'desc');
})->get()->first();
You must have got error when using order_by as its not the syntax in Laravel.
$localnews = Articles::whereHas('sous_categories',
function ($query) {
$query->where('id', '15')->orderBy('created_at', 'desc');
})->first();
Please have a look at official documentation to help you with.
And when using first() you don't need to use get().
get() we use to fetch multidimensional associative array.
first() we use to fetch one record which matches first.
Here is concise difference between all functions you will use then after. link.
It should be like this,
$localnews=Articles::whereHas('sous_categories', function($query) {
$query->where('id', '15')->orderBy('created_at', 'desc');
})->firstOrFail();

Laravel wherehas ignored when using with

I have a Query where I want to see all Alert (relation) items for a User for a specific type.
I'm using the following query
$users = User::with('alerts')->whereHas('alerts', function($q) use ($type) {
$q->where('type', $type);
})->get();
The issue is it's ignoring my where subquery and returning the alerts for all types, not the type I'm passing into the whereHas.
Thank you!
Solution
whereHas limits the results of User, not the results of alerts
I had to use a subquery on the 'with' statement.
$users = User::whereHas('email_alerts')->with(['email_alerts' => function($q) use ($email_type) {
$q->where('email_type', $email_type);
}, 'company'])->get();

Laravel fetch data from model where the condtions is from another model

I have a table called List which i planned to be displayed into view with this command : $lists= List::with('user', 'product.photodb', 'tagCloud.tagDetail')->get();. But, i want the data displayed is only those that has TagID equal to the one user inputted. Those data can be retrieved from TagCloud table.
What i am currently doing is :
$clouds = TagCloud::select('contentID')
->where('tagDetailID', '=', $tagID)
->get();
$lists = List::with('user', 'product.photodb', 'tagCloud.tagDetail')
->where('id', '=', $clouds->contentID)
->get();
But when i tried to run it, it only return a null value, even though when i am doing return $clouds, it does returned the desired ID.
Where did i do wrong ? Any help is appreciated !
A couple of gotchas with your current solution.
Using get() returns an Illuminate\Database\Eloquent\Collection object. Hence you can't use $clouds->contentID directly since $clouds is a collection (or array if you prefer). See Collection Documentation.
where(...) expects the third parameter to be a string or integer, aka single value. Instead, you are passing a collection, which won't work.
The correct way is to use whereHas() which allows you to filter through an eager loaded relationship.
Final Code:
$lists = List::with('user', 'product.photodb', 'tagCloud.tagDetail')
->whereHas('tagCloud',function($query) use ($tagID) {
return $query->where('contentID','=',$tagID);
})
->get();
See WhereHas Documentation.
What you want is whereHas()
$list = List::with(...)
->whereHas('relation', function($q) use($id) {
return $q->where('id', $id);
})->get();
Apply Where condition in you tagCloud model method tagDetail
public function tagDetail(){
return $q->where('id', $id);
}

Different values when use DB::raw() in second param on where()

I have next query in Laravel Eloquent:
$buildings = Building::select('buildings.*')->join(
DB::raw('('.
(
IngameBuilding::select('buildings.building_id', 'buildings.level')
->join('buildings', 'buildings.id', '=', 'ingame_buildings.building_id')
->toSql()
).
') as `added_buildings`'), 'added_buildings.building_id', '=', 'buildings.building_id')
->where('buildings.level', '>', 'added_buildings.level')
->get();
This query returns all allowed rows from base, but one row more. When I added DB::raw() in where() return values is valid.
Good-working code:
$buildings = Building::select('buildings.*')->join(
DB::raw('('.
(
IngameBuilding::select('buildings.building_id', 'buildings.level')
->join('buildings', 'buildings.id', '=', 'ingame_buildings.building_id')
->toSql()
).
') as `added_buildings`'), 'added_buildings.building_id', '=', 'buildings.building_id')
->where('buildings.level', '>', DB::raw('`added_buildings`.`level`'))
->get();
Why first code workig, hmm.. Wrong?
I'm not a big fan of Laravel at all.
I've got only small experience with this framework but i'm almost sure that where function accepts only a 'constant' values to be checked against.
If you'll get an output of this query using toSQL method on the query object you will see that eloquent will convert it as something like:
(...) where buildings.level > 'added_buildings.level'
so the condition checks if the buildings.level (whatever the type is)
is greater than the given string and not the column value.
Using the DB::raw you're getting the proper sql as the eloquent won't parse/convert it.
You would need to use whereRaw method I suppose.
http://laravel.com/docs/4.2/queries#introduction

Categories