This question already has answers here:
Laravel OrderBy Random
(4 answers)
Closed 2 years ago.
Usecase: Show top 3 featured images randomly then followed by non featured images with paginating. I have around 17 featured images.
How I can random with orderBy.
DB:featured: 0 or 1 in DB
$images = Images::OrderBy('featured', 'desc')->paginate(10);
Try
Without Pagination
//Latest 3 featured images
$top3FeaturedImages = Images::where('featured', 1)
->latest()
->take(3)
->get();
$randomUnfeaturedImages = Images::where('featured', 0)
->inRandomOrder()
->take(7)
->get();
$result = $top3FeaturedImages->concat($randomUnfeaturedImages);
With Pagination
$featuredImages = Images::where('featured', 1)
->latest()
->take(3)
->get();
$randomUnfeaturedImages = Images::where('featured', 0)
->inRandomOrder()
->paginate(7);
//In this case you need to pass 2 variables to the view $featuredImages & paginated $randomUnfeaturedImages
Related
In my code, i am querying a database by accepting month and year input from user.
I have tried writing it the normal PHP way and other ways i can find online but none seems to be working. here is the code i am using currently
$salesmonth = $request->input('mn');
$salesyear = $request->input('yr');
$id = Auth::user()->id;
$comm = \DB::table('bakerysales')
->where([
['customer_id', '=', $id], [MONTH('sales_date'), '=', $salesmonth], [YEAR('sales_date
'), '=', $salesyear]
])
->get();
return view::make('showCommission')->with('comm', $comm);
I expect the query to return data from rows that match user selected month and year
Laravel comes with a few different where clauses for dealing with dates e.g.
whereDate / whereMonth / whereDay / whereYear.
This means that your controller method can look something like:
$comm = \DB::table('bakerysales')
->where('customer_id', auth()->id())
->whereMonth('sales_date', $request->input('mn'))
->whereYear('sales_date', $request->input('yr'))
->get();
return view('showCommission', compact('comm'));
I have two tables questions and answers. Question table has relationship on answer table.
When paginating eloquent results on the first page it returns lets say 7 unanswered questions (with empty relationship) and 3 with answered questions, but I need it to return 5 with answers and 5 without answers in total 10.
Right now i'm doing this:
Question::with(['user', 'answers])->paginate(10);
Is there any way to return always 5 answered/5 unanswered instead of random?
The paginate() method returns a LengthAwarePaginator object so you can create your own as the doc suggests. Maybe (I haven't tested it) you can do it more or less like this:
$limit = $request->input('limit', 5);
$page = $request->input('page', 1);
$total = Question::count();
$offset = ($page - 1) * $limit;
$items1 = Question::with(['user', 'answers'])->has('answers')->limit($limit)->offset($offset)->get();
$items2 = Question::with(['user', 'answers'])->doesntHave('answers')->limit($limit)->offset($offset)->get();
$paginator = new \Illuminate\Pagination\LengthAwarePaginator(
$items1->concat(items2),
$total,
$limit,
$page,
['path' => $request->getPathInfo()]
);
return response()->json($paginator);
I'm trying to work on a chart with a few datasets, however for the purposes of asking this question, I will only include one.
At the moment if I have the following in my controller:
$maintenancesForklifts =
DB::table("equipment_attachments")
->join('equipment as equip', 'equip.id', '=', 'equipment_attachments.unitID')
->select(DB::raw('year(date) as year'), DB::raw("COUNT(*) as count"))
->where('attachmentCategory','Maintenance')
->where('equip.unit_type',3)
->orderBy(DB::raw("year(date)"))
->groupBy(DB::raw("year(date)"))
->get();
I will get this returned:
[{"year":2005,"count":2},{"year":2006,"count":2},{"year":2010,"count":4},{"year":2011,"count":1},{"year":2012,"count":2},{"year":2013,"count":1},{"year":2014,"count":10},{"year":2015,"count":7},{"year":2016,"count":6},{"year":2017,"count":19},{"year":2018,"count":4}]
As you can see there are a few years missing if I went from say 2000 to the present day. Do you know how I could return the results so that they would come back with the years that have a zero count?
One way you could do this:
$years = collect(range(2000, now()->format('Y')))->map(function ($year) use ($maintenancesForklifts) {
return $maintenancesForklifts->firstWhere('year', $year) ?? (object)['year' => $year, 'count' => 0];
});
I have a query
$orders = DB::table('orders')->where('user_id', $user->id)->get();
And this is what I have in view:
#foreach ($orders as $order)
{{ $order->id }}
#endforeach
It prints out 1 2 3, because the table has these three IDs.
But if I try to join, I get a rather unpredicted result.
$orders = DB::table('orders')->where('user_id', $user->id)->
leftJoin('status', 'orders.status_id', '=', 'status.id')
->get();
It gives 2 1 1. Result is the same with rightJoin() and join().
I thought this command would append row from status table to every corresponding row of orders table. Join on orders.status_id = status.id.
Can I get an intended result?
I have tried ->select('orders.*') but it did not change the result.
But still, I needed to alias everything out, as suggested in the comments here. So here is my final query.
$orders = User::find($user->id)->orders()->
select('orders.id as order_id', 'status.id as status_id',
'status.label as label', 'orders.ordered_at as ordered_at')
->leftJoin('status', 'orders.status_id', '=', 'status.id')
->get();
Probably this could be done in more pretty way, but this works.
Thank you who commented the post.
UPD: Now, I have fixed relations between my models and I can do this much simpler. As described here Laravel Many-to-one relationship
$orders = Order::with('status')->where('user_id', '=', $user->id)->get();
This question already has an answer here:
How to optimize code in Laravel?
(1 answer)
Closed 6 years ago.
I have the following code in Laravel, I get collection from request with a joined table translate.
That to get value from joined table I should use additional loop to format array which will be added to select list in blade template :
$arr = [];
$objectModel = new PlacesType();
$objectModel::$language = 2;
$subcategories = $objectModel::with("translate")->get();
foreach($subcategories as $key => $item){
$arr[$item->translate()->first()->objectId] = $item->translate()->first()->title;
}
return $arr;
So, how can I improve this code and escape this loop:
foreach($subcategories as $key => $item){
$arr[$item->translate()->first()->objectId] = $item->translate()->first()->title;
You could use mapWithKeys I guess?
https://laravel.com/docs/5.3/collections#method-mapwithkeys