Laravel order by for each column? - php

I am new to laravel, and i try to orderBy the rand, is it possible to order by in each column ? my code just take row rand but it dont shuffle the column just the row.
public function show(){
$name = DB::table('names')
->inRandomOrder()
->get();
return view('content', ['names' => $names]);
}

orderBy in Laravel.
The orderBy method allows you to sort the result of the query by a given column. The first argument to the orderBy method should be the column you wish to sort by, while the second argument controls the direction of the sort and may be either asc or desc:
$users = DB::table('users')
->orderBy('name', 'desc')
->get();
In your case this will work.
public function show(){
$names = DB::table('names')
->orderBy('name', 'desc')
->orderBy('city', 'asc')
->get();
return view('content', ['names' => $names]);

You Can Do Like This For To Order by in each column
public function show(){
$names = DB::table('names')
->orderBy('name', 'DESC')
->orderBy('city', 'DESC')
->orderBy('email', 'ASC')
->get();
return view('content', ['names' => $names]);
}
With foreach
$names = DB::table('names');
foreach ($request->get('order_by_columns') as $column => $direct) {
$names->orderBy($column, $direct);
}
$results = $names->get();

Related

Laravel Relationship Property Does Not Exist In This Collection Instance

$category = Category::orderBy('category_name_en', 'ASC')
->get();
$subcategory = SubCategory::where('category_id', $category->id)
->orderBy('subcategory_name_en', 'ASC')
->get();
$subsubcategory = SubSubCategory::where('subcategory_id', $subcategory->id)
->orderBy('subsubcategory_name_en', 'ASC')
->get();
return view('welcome', compact('category', 'subcategory', 'subsubcategory'));
In this above code we are getting error:
Property [id] does not exist on this collection instance.
Why is this error showing?
That's because you are returning a Collection whenever you write get.
Try this instead:
$category = Category::orderBy('category_name_en', 'ASC')
->get();
$subcategory = SubCategory::whereIn('category_id', $category->pluck('id'))
->orderBy('subcategory_name_en', 'ASC')
->get();
$subsubcategory = SubSubCategory::whereIn('subcategory_id', $subcategory->pluck('id'))
->orderBy('subsubcategory_name_en', 'ASC')
->get();
return view('welcome', compact('category', 'subcategory', 'subsubcategory'));
The changes being where converted to whereIn, and ->id becomes ->pluck('id').
As you can see from the documentation, whereIn accepts an array of values for it's second argument, and pluck will return an array of, in our case, IDs.
Combining these will mean that category_id will need to exist within the array.
If, however, these models were supposed to supply a single Model.
Then you should do the following:
$category = Category::orderBy('category_name_en', 'ASC')
->first();
$subcategory = SubCategory::where('category_id', $category->id)
->orderBy('subcategory_name_en', 'ASC')
->first();
$subsubcategory = SubSubCategory::where('subcategory_id', $subcategory->id)
->orderBy('subsubcategory_name_en', 'ASC')
->first();
return view('welcome', compact('category', 'subcategory', 'subsubcategory'));
This is using the first method to return a single instance.

Call to a member function where() on array laravel

I have two tables tbl_law_master & tbl_law_sub_master
on both these tables there is a column named as assigned_to, this column stores user's id.
my task is to get sublaw from tbl_law_sub_master for particular user's id by joining law_id of tbl_law_master.
this is my code,
$law_id = $_GET['law_id'];
$sublaw = DB::table('tbl_law_sub_master')
->select('tbl_law_sub_master.*', 'tbl_law_master.lm_id', 'tbl_law_master.law_name', 'tbl_law_master.id as lawId')
->leftJoin('tbl_law_master', 'tbl_law_master.id', '=', 'tbl_law_sub_master.lm_id')
->where('tbl_law_sub_master.lm_id', $law_id)
->orderBy('type_of_event', 'asc')
->orderBy('section', 'asc')
->orderBy('rules', 'asc')
->orderBy('notification', 'asc')
->orderBy('circular', 'asc')->get();
if (!in_array(Auth::user()->role, [1, 7]))
{
$sublaw = $sublaw->where('tbl_law_master.assigned_to', Auth::user()->id);
}
it shows me error as
Call to a member function where() on array
The problem is that you already called get() of your query then called where() again.
You should use where clause function like this
$sublaw = DB::table('tbl_law_sub_master')
->select('tbl_law_sub_master.*', 'tbl_law_master.lm_id', 'tbl_law_master.law_name', 'tbl_law_master.id as lawId')
->leftJoin('tbl_law_master', 'tbl_law_master.id', '=', 'tbl_law_sub_master.lm_id')
->where(function($query) use ($law_id) {
$query->where('tbl_law_sub_master.lm_id', $law_id);
if (!in_array(Auth::user()->role, [1, 7]))
{
$query->where('tbl_law_master.assigned_to', Auth::user()->id);
}
})
->orderBy('type_of_event', 'asc')
->orderBy('section', 'asc')
->orderBy('rules', 'asc')
->orderBy('notification', 'asc')
->orderBy('circular', 'asc')->get();
I think you should call get after the last where statement
$sublaw = DB::table('tbl_law_sub_master')
->select('tbl_law_sub_master.*', 'tbl_law_master.lm_id', 'tbl_law_master.law_name', 'tbl_law_master.id as lawId')
->leftJoin('tbl_law_master', 'tbl_law_master.id', '=', 'tbl_law_sub_master.lm_id')
->where('tbl_law_sub_master.lm_id', $law_id)
->orderBy('type_of_event', 'asc')
->orderBy('section', 'asc')
->orderBy('rules', 'asc')
->orderBy('notification', 'asc')
->orderBy('circular', 'asc');
if (!in_array(Auth::user()->role, [1, 7]))
{
$sublaw = $sublaw->where('tbl_law_master.assigned_to', Auth::user()->id)->get();
}

How to pass an array of IDs from one Laravel query to another

I have 2 queries from two different tables. First one contains the IDs which I would like to use in the second query. For now I do it like this. I extract the IDs into a new array, and then use this array in ->whereIn() in second query.
$campaign = DB::connection('mysql2')->table('mc_spots')
->select('s_customer', 's_product', 'spotid')
->where('s_starttermin', '>=', date("Y-m-d", strtotime($dateFrom)))
->where('s_lastrun', '<=', date("Y-m-d", strtotime($dateUntil)))
->where('s_media', '=', $media)
->where(function ($query) use ($products) {
for ($i = 0; $i < count($products); $i++) {
$query->orwhere('s_product', '=', $products[$i]);
}
})
->get();
$campaignID = [];
foreach ($campaign as $c) {
array_push($campaignID, $c->spotid);
}
$table = DB::connection('mysql2')->table('schaltdaten_tv_de')
->select('*')
->join('epgdata_channel', 'schaltdaten_tv_de.cid', '=', 'epgdata_channel.channelid')
->join('mc_spots', 'schaltdaten_tv_de.ReferenceDescription', '=', 'mc_spots.spotid')
->whereIn('ReferenceDescription', $campaignID)
->groupBy('epgdata_2013.id')
->orderBy('StartofBreak', 'ASC')
->limit(500)
->get();
Is there more convenient way to do this without looping through every item of $campaign?
You need to pluck id from first query which gives you array of ids and you can use it in second query.
$campaign = DB::connection('mysql2')->table('mc_spots')
->select('s_customer', 's_product', 'spotid')
->where('s_starttermin', '>=', date("Y-m-d", strtotime($dateFrom)))
->where('s_lastrun', '<=', date("Y-m-d", strtotime($dateUntil)))
->where('s_media', '=', $media)
->where(function ($query) use ($products) {
for ($i = 0; $i < count($products); $i++) {
$query->orwhere('s_product', '=', $products[$i]);
}
})
->pluck('spotid');
Now, use spot id array in whereIn of second as ,
$table = DB::connection('mysql2')->table('schaltdaten_tv_de')
->select('*')
->join('epgdata_channel', 'schaltdaten_tv_de.cid', '=', 'epgdata_channel.channelid')
->join('mc_spots', 'schaltdaten_tv_de.ReferenceDescription', '=', 'mc_spots.spotid')
->whereIn('ReferenceDescription', $campaign)
->groupBy('epgdata_2013.id')
->orderBy('StartofBreak', 'ASC')
->limit(500)
->get();
Hope you understand
You can do it like this
$campaignID = $campaign->pluck('spotid');
Pluck doc:
The pluck method retrieves all of the values for a given key
And as Sagar said, it retrieves an array which is the second argument to our ->whereIn()
You can do this by use of array_column()
Like this
$campaignID=array_column($campaign,'spotid')
Make sure that $campaign must be an array. if it is object the convert it into array like this json_decode(json_encode($campaign),true)
For exapmle
$t='[{"id":49},{"id":61},{"id":5},{"id":58}]' ;
array_column(json_decode($t,true),'id')
It will give output as
As you're already joining the mc_spots table in the 2nd query you could always just add the same constraints from the 1st query:
$table = DB::connection('mysql2')->table('schaltdaten_tv_de')
->select('*')
->join('epgdata_channel', 'schaltdaten_tv_de.cid', '=', 'epgdata_channel.channelid')
->join('mc_spots', 'schaltdaten_tv_de.ReferenceDescription', '=', 'mc_spots.spotid')
->where('mc_spots.s_starttermin', '>=', \Carbon\Carbon::parse($dateFrom))
->where('mc_spots.s_lastrun', '<=', \Carbon\Carbon::parse($dateUntil))
->where('mc_spots.s_media', $media)
->whereIn('s_product', $products)
->groupBy('epgdata_2013.id')
->orderBy('StartofBreak', 'ASC')
->limit(500)
->get();
Hope this helps!

whereHas query in Laravel

Hello guys,
$filterArray = explode("_", $filters);
$data['articles'] = \DB::table('products')->join('product_category', function ($q) {
$q->on('product_category.product_id', '=', 'products.id');
})->where('product_category.category_id', '=', $id)
->select('products.*')
->whereBetween('price_retail_1', array($priceFrom, $priceTo))
->whereHas('filters', function ($query, $filterArray) {
$query->whereIn('filter_id', $filterArray);
})
->orderBy('products.' . $sort, $sortOrder)
->get();
}
I have the following query and I'm having some issues on the whereHas method. I'm getting an error
Unknown column 'has' in 'where clause
most likely because the $filterArray variable is out of scope for the function ( or at least that is what I am guessing. Any help on how to solve the issue is appreciated.
You cannot use whereHas method in the Query Builder context. The whereHas method is only for Eloquent Query Builder that is comming from the Eloquent models and their relationships.
What you can do is to use joins. So you can try like this:
$filterArray = explode("_", $filters);
$data['articles'] = \DB::table('products')->join('product_category', function ($q) {
$q->on('product_category.product_id', '=', 'products.id');
})->where('product_category.category_id', '=', $id)
->select('products.*')
->whereBetween('price_retail_1', array($priceFrom, $priceTo))
->join('filters', 'products.filter_id', '=', 'filters.filter_id')
->whereIn('filter_id', $filterArray);
->orderBy('products.' . $sort, $sortOrder)
->get();
I don't know how you connecting these two tables so here is only the example data:
->join('filters', 'products.filter_id', '=', 'filters.filter_id')

getting database results from an array of ids [duplicate]

I'm trying to execute IN statement in Eloquent query. I tried this:
$id = urldecode($id);
$news = News::whereHas('newsCategories', function($q) use($id)
{
$q->where('category_id', 'IN', '('.$id.')')->orderBy('created_at', 'desc');
})->get();
But I get empty result.
When I switch IN for = and pass a number instead of array I get results. Did I do something wrong?
So this works:
$id = 2;
$news = News::whereHas('newsCategories', function($q) use($id)
{
$q->where('category_id', '=', $id)->orderBy('created_at', 'desc');
})->get();
You want whereIn with an array of your ids to be checked...
$news = News::whereHas('newsCategories', function($q) use($array_of_ids)
{
$q->whereIn('category_id', $array_of_ids)
->orderBy('created_at', 'desc');
})->get();
Just make sure that you're passing in something that is truly an array :)

Categories