whereBetween passing array - laravel

Hi I have query where I want to pass an array to whereBetween query.
for example I have an array which looks like this
Array
(
[product_id] => Array
(
[0] => 31337
[1] => 31366
)
[lands] => Array
(
[0] => 12
[1] => 23
)
)
Now I want search those product_id which are between [0] => 31337 and [1] => 31366 and same goes to land I want to find the lands where Between [0] => 12 and [1] => 23
now say I have a variable $filters which has the this above array in it and I pass it like this to the query like below.
public function scopeDynamicInBetweenFilter($query, $filters)
{
if(!empty($filters)){
return $query->whereBetween($filters);
}
return $query;
}
It gives me an error
Type error: Too few arguments to function Illuminate\Database\Query\Builder::whereBetween(), 1 passed and at least 2 expected
it does like this at
Builder->whereBetween('product_id' => array('31337', '31366'))->whereBetween('lands' => array('12', '23'))
what could be done to achieve this.

You could try to loop through the filters and apply it to the query
public function scopeDynamicInBetweenFilter($query, $filters)
{
if(! empty($filters)) {
if (is_array($filters)) {
foreach ($filters as $key => $value) {
$query->whereBetween($key, $value);
}
}
}
return $query;
}

Try this:
if(!empty($filters)){
return $query->whereBetween('product_id', $filters['product_id'])->whereBetween('lands', $filters['lands']);
}

Related

Import CSV file, remove empty rows and export it immediately without storing it into database - laravel excel

I am trying to remove all the empty rows from a csv and make it downloadable. In this process, there is no involvement of database/model.
My flow looks like:
1) Import csv file.
2) Filter empty rows.
3) Export the data after all the empty rows are removed.
My code looks like:
Controller
public function formatCSV()
{
$path = storage_path('app/files/') . 'example.csv';
Excel::import(new FormatCSV, $path);
}
app/Imports/FormatCSV
<?php
namespace App\Imports;
use App\Exports\ExportFormattedCSV;
use App\Http\Services\AmenityService;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Excel;
class FormatCSV implements ToArray, WithChunkReading
{
private $table,$service,$model;
public function __construct()
{
$this->service = new AmenityService();
}
public function array(Array $rows)
{ $rec_arr = array();
foreach ($rows as $row)
{
$rec_arr[] = array_values($row);
}
$records_arr = $this->service->trimArray($rec_arr);
$export = new ExportFormattedCSV($records_arr);
//print_r($export);
return Excel::download($export, 'csv.csv');
}
public function chunkSize(): int
{
return 10;
}
}
trimArray function
public function trimArray($arr)
{
$final = array();
foreach($arr as $k => $v)
{
if(array_filter($v)) {
$final[] = $v;
}
}
return $final;
}
app/Exports/ExportFormattedCSV
<?php
namespace App\Exports;
use Maatwebsite\Excel\Concerns\FromArray;
class ExportFormattedCSV implements FromArray
{
protected $data;
public function __construct(array $data)
{
$this->data = $data;
}
public function array(): array
{
return $this->data;
}
}
With this code it does nothing, shows blank at the end.
However, if I uncomment the line print_r($export)
It shows data as:
App\Exports\ExportFormattedCSV Object
(
[data:protected] => Array
(
[0] => Array
(
[0] => First Name
[1] => Last Name
[2] => Roll No
)
[1] => Array
(
[0] => Ram
[1] => Patel
[2] => 1
)
[2] => Array
(
[0] => Rajuv
[1] => Roy
[2] => 2
)
[3] => Array
(
[0] => Sunny
[1] => Deol
[2] => 5
)
[4] => Array
(
[0] => Akshya
[1] => Kumar
[2] => 6
)
[5] => Array
(
[0] => Amir Khan
[1] => 7
[2] =>
)
[6] => Array
(
[0] => Salman
[1] => Khan
[2] => 9
)
[7] => Array
(
[0] => Bobby
[1] => Deol
[2] => 10
)
)
)
The File I am testing is example.csv
First Name,Last Name, Roll No
Ram,Patel,1
Rajuv,Roy,2
,,
Sunny,Deol,5
Akshya,Kumar,6
Amir Khan,7
,,
Salman,Khan,9
Bobby,Deol,10,
Barun,Dhawan,11
,,
Virat,Kohli,13
Rohit,Sharma,14

I need To All Data In $qryy It Return Only Last Record

How I Return all data of $qryy it's return me only last record. How I need return all off data.
public function get_subcategory(){
$qry = $this->db->get("shopping_category");
foreach($qry->result() as $row){
$this->db->where("c_id",$row->id);
$qryy = $this->db->get("shopping_subcategory");
}
return $qryy;
}
You can try this
public function get_subcategory() {
$result = [];
$qry = $this->db->get("shopping_category");
foreach ($qry->result() as $row) {
$this->db->where("c_id", $row->id);
$qryy = $this->db->get("shopping_subcategory");
$result[] = $qryy;
}
return $result;
}
The reason you get the last record is, every time you loop data through foreach it keeps replacing $qryy = $this->db->get("shopping_subcategory");
to fix this you can simply change $qryy into an array $qryy[] like this.
To improve your query. you can simply try
$qryy = [];
$this->db->select("shopping_subcategory.*");
$this->db->from("shopping_category");
$this->db->join('shopping_subcategory', 'shopping_category.id = shopping_subcategory.c_id');
$sql= $this->db->get();
$qryy = $sql->result_array();
$data['category'] = $qryy;
$this->load->view('view_name', $data);
In view
$category will show your data
I think it solve your problem. would you mind if you give it a try?
since you want from table shopping_category is only id i try to fetch it so it's not a heavy duty on your server.
$result = [];
$qry = $this->db->select("id")->get('shopping_category');
foreach ($qry->result() as $row) {
$this->db->where("c_id", $row->id);
$qryy = $this->db->get("shopping_subcategory")->result();
$result[] = $qryy;
}
return $result;
Hope that helps :)
you should use another approach to resolve your problem: use joins to query the database only once:
$this->db->join("shopping_subcategory t2","t2.c_id=t1.id");
$qry = $this->db->get("shopping_category t1");
return $qry->result();
if you output above with print_r($qry->result()), you get similar to below:
Array
(
[0] => stdClass Object
(
[ID] => 1
[company_ID] => 1
[name] => aaa
)
[1] => stdClass Object
(
[ID] => 2
[company_ID] => 1
[name] => bbb
)
[2] => stdClass Object
(
[ID] => 4
[company_ID] => 2
[name] => ccc
)
)
to resolve your approach: you need to make $qryy an array, to store each subquery data, right now you are overwriting the variable $qryy with each loop and therefore only get the last result:
$qry = $this->db->get("shopping_category");
$qryy=array();
foreach($qry->result() as $i=>$row){
$this->db->where("c_id",$row->id);
$qryy[$i] = $this->db->get("shopping_subcategory")->result();
}
return $qryy;
if you output above with print_r($qryy), you get similar to below:
Array
(
[0] => Array
(
[0] => stdClass Object
(
[ID] => 1
[company_ID] => 1
[name] => aaa
)
[1] => stdClass Object
(
[ID] => 2
[company_ID] => 1
[name] => bbb
)
)
[1] => Array
(
[0] => stdClass Object
(
[ID] => 4
[company_ID] => 2
[name] => ccc
)
)
)
therefore, depending which approach you use, you'll need to take care of your data output differently.
helpful info on joins here

How to create a single array using two iterating loop and than update_batch

How do I take id on every iteration from check_seeds array and add on each itteration into seeded[] array.
In more simple words, I want to take an item from the first iteration and add into the first iteration, take an item from the second iteration and add into the second iteration and so on...
Actually, on update_batch we need third parameter (primary key, index) to update array values in database rows where id from database rows matches with the id in update_batch.
$check_seeds = $this->tournament_model->get_seeds($tournament_id);
$seeds = $this->input->post('seed');
foreach ($seeds as $key => $value){
if(!empty($key) && !empty($value)){
$seeded[] = array(
'id' => (Add id here),
'tournament_id' => $tournament_id,
'stage_id' => $stage_id,
'seed_id' => $value,
'team_name' => $key,
);
$this->db->update_batch('tournament_seed', $seeded, 'id');
redirect('organizer/tournaments);
}
}
print_r($check_seeds)
Array
(
[0] => Array
(
[id] => 3
[tournament_id] => 713161746
[stage_id] => 3
[seed_id] => 3
[team_name] => -V-ATTAX
)
[1] => Array
(
[id] => 4
[tournament_id] => 713161746
[stage_id] => 3
[seed_id] => 3
[team_name] => -V-ATTAX
)
[2] => Array
(
[id] => 5
[tournament_id] => 713161746
[stage_id] => 3
[seed_id] => 3
[team_name] => -V-ATTAX
)
)
in your model function get_seeds() you can query the current max value of id as an alias and return it together with the query result:
function get_seeds($tournament_id) {
$this->db->select_max('id', 'max_id');
$this->db->where('tournament_id', $tournament_id);
$result = $this->db->get('tournament_seed');
return $result->result();
}
then in your controller's for_each() you increment that value:
$i=0;
foreach ($seeds as $key => $value){
$i++;
$seeded[] = array(
'id' => $value->max_id + $i,
//....
);
}
Codeigniter docs: Selecting Data, scroll down to select_max(), as there is no internal bookmark

codeignite trying to get property of non-object not resolved

I am attempting to access the result set from a model query in the view. I have the following:
Controller:
$courseId = $this->session->userdata('courseId');
//echo "Course: ".$courseId;
if(isset($courseId) && $courseId != '')
{
$result = $this->Course_model->loadBasicDetailsEdit($courseId);
$data['basicCourseDetails'] = $result;
$this->load->view('course/basicDetails', $data);
}
Model:
function loadBasicDetailsEdit($courseId)
{
$this->db->select('*');
$this->db->where('course_id', $courseId);
$this->db->from('course');
$query = $this->db->get();
if ( $query->num_rows() > 0 )
{
return $query->result();
} else {
return FALSE;
}
}
and in the view I tried to print_r() and got this:
Array ( [0] => stdClass Object ( [course_id] => 8 [title] => Photography [summary] => [description] => [price] => [member_id] => 12 [category] => [audience] => [goals] => [date] => 2013-09-26 [production] => 0 ) )
I tried to access this using $basicCourseDetails->title or $basicCourseDetails['title']
but neither are working. Any hint as to why this is happening?
Regards,
try this:
foreach($basicCourseDetails as $basic){
echo($basic->title);
}
or something like this:
echo($basicCourseDetails[0]->title);
This is an array of objects
Array ( [0] => stdClass Object ( [course_id] => 8 [title] => Photography [summary] => [description] => [price] => [member_id] => 12 [category] => [audience] => [goals] => [date] => 2013-09-26 [production] => 0 ) )
Contains one stdObject in the array, so, first objects is 0, if there were more, then second item could have index 1 and so on. To retrieve data from the first (here is only one) stdobject you may use
echo $basicCourseDetails[0]->title; // title will be printed
You can send data to the view page by this line of code which is mentioned in above question.
$result = $this->Course_model->loadBasicDetailsEdit($courseId);
$data['basicCourseDetails'] = $result;
$this->load->view('course/basicDetails', $data);
But when you will access these data in view then you need to access all data one by one by using foreachloop in the view page.
For example if you have a view page like basic_details.php inside course folder then you need to write code like this to access these data.
foreach ($basicCourseDetails as $key => $value) {
$name = $value->name;
}
The above foreachloop can be written in view page where you want to access data.

Best way to make selects in laravel?

In order to use the Form::select, you need to add a name and two arrays.
In a normal case, we have one with the id and another one with the name. Both needs to be loaded from a query.
So in the model I have something like this:
public static function get_ids()
{
//return DB::query('select id FROM __roles');
return DB::table('roles')->get(array('id'));
}
//Returns an array with all the names
public static function get_names()
{
//return DB::query('select name FROM __roles');
return DB::table('roles')->get(array('name'));
}
However, this gives me this:
Array ( [0] => stdClass Object ( [id] => 1 ) [1] => stdClass Object ( [id] => 2 ) [2] => stdClass Object ( [id] => 3 ) )
I would like to get something like this:
Array ( [0] => '1' [id] => '2' [id] => '3' )
For the form
Form::select('role', array(Role::get_ids(), Role::get_names()));
Does this work?
public static function get_ids()
{
//return DB::query('select id FROM __roles');
return DB::table('roles')->get(array('id'))->to_array();
}
//Returns an array with all the names
public static function get_names()
{
//return DB::query('select name FROM __roles');
return DB::table('roles')->get(array('name'))->to_array();
}
I tried this option:
$projects = Project::where('user_id', Auth::user()->id)->lists('name', 'id');
In template:
{{ Form::select('project', $projects) }}

Resources