John Davidson

php - Get empty columns in laravel collection

0 comments
Message:


I have this Laravel collection, obtained from a DB query:


$c = collect(\DB::connection('mysql_scipg')
->table('producao_email')
->where('cod_cliente', $cliente_id)
->where('lote',$lote)
->whereIn('cod_status',$statusCliente)
->select('dominio','lote','sv_email','cod_status')
->get());

The problem i'm encountering is, getting data from the collection, in cases where sv_email is different of "":


example:


there are cases where sv_email is filled in and cases where sv_email = "", sv email is either with information or "", note is not null, it is " ";


in the image below, I presented a case where sv_email = ""


using the command:


dd ($c-> where ('sv_email', '')

collection where sv_email = ""


I tested the command dd($c->where('sv_email','SVV095')


collection where sv_email != ""


the problem occurs when I try to get sv_email, in cases where it is different from ""


I tested:



dd($c->where('sv_email','<>',"");
dd($c->where('sv_email','<>','');
dd($c->where('sv_email','!=',"");
dd($c->where('sv_email','!=','');


all returned an empty collection.


there is a case where it returns as I wish. But I have to do another query, and I don't want this way, because I would have to do 2 queries in the DB to get the data, and I can manipulate the collection, where am I going wrong?


the case where it works would be:



$c_2 = collect(\DB::connection('mysql_scipg')
->table('producao_email')
->where('cod_cliente', $cliente_id)
->where('lote',$lote)
->where('sv_email','!=','')
->select('dominio','lote','sv_email','cod_status')
->get());



My Answer:
To get the empty columns in the Laravel collection, you can use the `filter` method along with a callback function. Here's an example of how you can achieve this:

php
$emptyColumns = $c->filter(function ($item) {
return $item->sv_email === '';
});

dd($emptyColumns);


This code snippet will filter the collection `$c` and return only the items where `sv_email` is an empty string. You can then use `dd` to dump and die the filtered collection.

Alternatively, if you want to get the non-empty columns, you can use the `reject` method:

php
$nonEmptyColumns = $c->reject(function ($item) {
return $item->sv_email === '';
});

dd($nonEmptyColumns);


This code snippet will reject the items where `sv_email` is an empty string and return the collection with non-empty `sv_email` values.

I hope this helps! Let me know if you have any further questions.

Rate this post

3 of 5 based on 9645 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us