Laravel counting database rows with same name field [closed] - laravel

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

Related

How can I make this query in laravel? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I can't find how to make this query
SELECT * FROM paquetes
WHERE (
SELECT estatuses.nombre FROM estatus_paquete
INNER JOIN estatuses ON estatuses.id = estatus_paquete.estatus_id
WHERE (estatus_paquete.paquete_id = paquetes.id)
ORDER BY estatus_paquete.created_at DESC LIMIT 1
) = 'En envio'
AND paquetes.deleted_at IS NULL
It's a tricky query, but you can make it line by line with the following syntax.
$query = DB::query()
->select('*')
->from('paquetes')
->where(function ($sub) {
$sub->select('estatuses.nombre')
->from('estatus_paquete')
->join('estatuses', 'estatuses.id', 'estatus_paquete.estatus_id')
->whereColumn(['estatus_paquete.paquete_id', 'paquetes.id'])
->orderByDesc('estatus_paquete.created_at')
->limit(1);
}, 'En envio')
->whereNull('paquetes.deleted_at');
// dump($query->toSql());
$query->get();

how can i reduce repeated code in laravel? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
i am new in laravel,
i have array like
{
music : {'a' =>1, 'b'=> 2},
video :{'c' =>10, 'd'=> 20}
}
i got this by using this code
$video = ResourcesVideo::where('resource_type', 'video')->get();
$music = ResourcesVideo::where('resource_type', 'music')->get();
$response['data'] = [
"videos" => $video,
"music" => $music,
];
on this code i got above array. so my quetions is.
how can i reduce that code. because many things are similer except where condition tried many ways but no success.
You can create array of resources and loop through it.. so in case there are more resource types in future you don't need to repeat code.
$resource_types = ['video', 'music'];
foreach ($resource_types as $resource_type) {
$resources[$resource_type] = ResourcesVideo::where([
'resource_type' => $resource_type,
])->get();
}
$response['data'] = $resources ?? [];

How to improve code Laravel? [duplicate]

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

SUPER SIMPLE LINQ to filter row does not work [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Spent about 4 hours trying to figure this out without success.
IQueryable<userTOM> Infolist = userTOMs();
var rbtUserId = Infolist.Where(x => x.UserName == FormsUserName);
userTOMs <-- Does not exist.
Remade the namespace many times but will not appear.
IQueryable does not run immediately on the database. In order to run the query, one has to run functions such as .ToList(), or .Count() on the IQueryable.
Therefore, nothing in your pasted code triggers the database request, and the ID will not be retrieved. I would modify your request to this:
IQueryable<userTOM> Infolist = userTOMs();
userTOM rbtUser = Infolist.FirstOrDefault(x => x.UserName == FormsUserName);
Guid rbtUserId; //assuming this will be populated with a Guid value
if (rbtUser != null) {
rbtUserId = rbtUser.Id; //assuming "ID" is the property name
}

how to use .Contains LINQ in decimal fields [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I need to filter by a field of type decimal. How Do I?
Here's how I do for string fields:
cartaoCredito.strCartaoCreditoDescricao.ToUpper().Contains(strParam.ToUpper())
Here is my method:
public List<CartaoCredito> GetCartaoCreditoByintCodigoGrupoUsuarioByFiltro(int intCodigoGrupoUsuario, string strParam)
{
return (from cartaoCredito in _DatabaseContext.CartaoCredito
where cartaoCredito.intCodigoGrupoUsuario == intCodigoGrupoUsuario && (cartaoCredito.strCartaoCreditoDescricao.ToUpper().Contains(strParam.ToUpper()))
select cartaoCredito).ToList();
}
I think you're trying to translate a call to string.Contains to a decimal value, which won't work, because decimal does not have a Contains method like string does.
If you have a collection of decimals and you want to see if a value is within that list, do something like:
List<decimal> list = {list of decimals}
var query = {source}.Where(x => list.Contains(x.{decimal property});
or if you just have a single value, you do not need Contains. Just do
decimal decParam = {some value};
var query = {source}.Where(x => x.{decimal property} = decParam);

Resources