How to improve code Laravel? [duplicate] - laravel

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

Related

Laravel counting database rows with same name field [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
imagine a table like this:
id
name
1
sam
2
lily
3
sam
4
tom
5
lily
i want to count the number of times that each name is repeated and store it in a variable.
expected result :count sam = 2 ,count lily = 2, count tom = 1
how can i do such thing in laravel?
Try this:
public function totalRepeatedName() {
$total = User::groupBy('name')
->selectRaw('count(*) as count, name')
->pluck('count', 'name');
return $total;
}
I'm assuming your model name is 'User'
$usernames = [];
$usercounts = [];
$names = User::->groupby('name')->get();
foreach ($names as $key => $name) {
$data = User::where('name', $name->name)->count();
array_push($usernames, $name->name);
array_push($usercounts, $data);
}
values will be available in $usernames and $usercounts. if you want them in same array use key value pair array

Order by featured DESC and Rand() - Laravel [duplicate]

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

How to get array of dates between two dates in laravel? [duplicate]

This question already has answers here:
PHP Carbon, get all dates between date range?
(11 answers)
Closed 2 years ago.
I want to get dates between two dates in an array. The scenario is the following: I want to get daily sales cash collection and there is one filter of $fromdate and $todate. So even if I don't get any sales for an specific date I have to show that in the table.
You can use CarbonPeriod for this.
I found something helpful at https://stackoverflow.com/a/50854594/13642447.
Use DatePeriod class to create the range of dates based on months or days
<?php
$begin = new DateTime( '2012-08-01' );
$end = new DateTime( '2013-10-31' );
$interval = new DateInterval('P1M');
$daterange = new DatePeriod($begin, $interval ,$end);
$dates = [];
foreach($daterange as $date){
$dates[] = $date->format("Y-m-d");
}
var_dump($dates);
?>
if you want the range of dates to be by days, say from 2012-08-01 to 2012-08-25 then just change the interval like this $interval = new DateInterval('P1D');.

Laravel 5.4 pagination with relationship

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

Codeigniter Query binding multiple fields with the same value

I'm in a situation where I'm doing a MySQL query with Codeigniter and where I have a lot of fields value request which are ALL the same.
Example:
$this->db->query('SELECT * FROM abc WHERE user_id = ? AND msg_from = ? AND msg_to != ?', [$id, $id, $id]);
This has just 3 question marks but the query I'm working on is HUGE and has 19 question marks WHICH ARE ALL THE SAME variable.
So I was trying to figure out how to tell Codeigniter all question marks are pointing to the same variable without having to fill an array with 19 times the same variable.
I thought of a for-loop but I wanted to know if a shortcut exist.
you should be able to do this with Codeigniters Query Builder pretty easily
Something like that should work:
$this->db
->select('*')
->from('abc');
$arrFields = array('users_id', 'msg_from', 'msg_to');
foreach($arrFields AS $val)
{
$this->db->where($val, $id);
}
$query = $this->db->get();

Resources