Laravel retreive data from database order by creation date - php

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();

Related

Eloquent make the query return null when related table found nothing

I am currently new in Eloquent and I am facing a problem here, I dont know the right terminologies when it comes to this, but currently this is my query
$mentor = $this->user->where("Role", "Mentor")->with(['article' => function ($query) use ($q) {
$query->where("cat_id", $q);
}])->get();
Yes, it works but thats not exactly the output I need, the article table returns empty as expected but I would like to the query to return empty when no article is found. How can I do that? This still returns data even when the article is null. Is what I wanted possible?
$mentor = $this->user->with('article')->where("Role", "Mentor")->whereHas('article', function ($query) use ($q) {
$query->where("cat_id", $q);
})->get();

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();

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

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

subquery in laravel - with()

I'm making a query using the following line:
$items = $this->model->with('subCategory')->get();
But I want to put a query inside the with() method, because I just want to get the items from with() where the status is equal to 0.
How can I achieve this?
There is an "eager loading" in L5 documentation. Here
$items = $this->model->with(['subCategory' => function ($query) {
$query->where('status', 0); }])->get();
These are called eagarload constraints, you can achieve your result using a closure
For example
$items = $this->model->with(['subCategory'=>function($q){
$q->whereId('5');
//or any other valid query builder method.
}])->get();
Let me know how you get on.

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

Categories