Monday, 23 January 2023

find value in comma separated string

 POSTGRESQL 

SELECT * FROM uploaded_data join WHERE '18' = any(string_to_array(user_id, ',')) 

With laravel

 $user_data = DB::select("SELECT id FROM uploaded_data WHERE '".Auth::user()->id."' = any(string_to_array(user_id, ',')) ");

 $user_data=collect($user_data)->pluck('id')->toArray();

 $data = UploadedData::whereIn('id', $user_data)->latest()->with('dataType')->with('state')->get();

MYSQL

$data = UploadedData::whereRaw('FIND_IN_SET(?, user_id)', [Auth::user()->id])->latest()->with('dataType')->with('state')->get();

Wednesday, 18 January 2023

Laravel get table column headings /list array

use Illuminate\Support\Facades\Schema; 

$cols = array_values(Schema::getColumnListing($tableName));

Laravel export data to excel with DB query , with dynamic table and dynamic columns using laravel excel



use Illuminate\Support\Facades\Schema;

use Illuminate\Support\Facades\DB;

1) controller function

 public function getExportData(Request $request,$tableName)

    {

        $headings=[];

        $cols = array_values(Schema::getColumnListing($tableName));

        if (($key = array_search("updated_at", $cols)) !== false) {

            unset($cols[$key]);

        }

        if (($key = array_search("created_at", $cols)) !== false) {

            unset($cols[$key]);

        }

        $selectedCols=$cols;

        foreach($cols as $headKey=>$headValue){

            $headValue=ucfirst($headValue);

            $headings[]=str_replace("_", " ",  $headValue);

        }

        return Excel::download(new FinalDataExport($tableName,$selectedCols,$headings), "$tableName.xlsx");

    }


2)  Export File

namespace App\Exports;

use Maatwebsite\Excel\Concerns\FromCollection;

use Maatwebsite\Excel\Concerns\FromQuery;

use Illuminate\Support\Facades\DB;

use Illuminate\Support\Facades\Schema;

use Maatwebsite\Excel\Concerns\WithHeadings;


class FinalDataExport implements FromCollection,WithHeadings

{

    public $table_name;

    public $selectedCols;

    public $headings;

    public function __construct($table_name,$selectedCols,$headings)

    {

        $this->table_name=$table_name;

        $this->selectedCols=$selectedCols;

        $this->headings=$headings;

    }

    public function collection()

    {

        return DB::table($this->table_name)->select($this->selectedCols)->orderBy('id','ASC')->get();

    }

    public function headings(): array

    {

        return $this->headings;

    }

}

Laravel Export data to csv

 use Illuminate\Http\Response; // Define a function to export data to CSV function exportToCSV($exportData, $columns) {     $filename = ...