Laravel excel export how to export conditional data? - laravel

I am trying to export partial data from my table not all data, I am using Maatwebsite plugin
I have tried below code in controller
public function report(Request $request)
{
$sdate = $request->query('sdate');
$edate = $request->query('edate');
$report = Report::whereDate('created_at', '>=', $sdate)
->whereDate('created_at', '<=', $edate)
->get();
return Excel::download($report, 'report.xlsx');
}
In this time I am getting empty excel file.
I am able to get all data after creating app/export
like below
app/export/ReportExport.php
public function collection()
{
return Report::all();
}
but how I can I do it in controller ? or how can I sent $report data controller to collection ?

You can use the FromQuery concern provided by the package.
namespace App\Exports;
use App\Report;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\Exportable;
class ReportExport implements FromQuery
{
use Exportable;
public function __construct($start, $end)
{
$this->start = $start;
$this->end = $end;
}
public function query()
{
return Report::query()->whereDate('created_at', '>=', $this->start)
->whereDate('created_at', '<=', $this->end);
}
}
Then from you controller, you can call it
return (new ReportExport($sdate, $edate))->download('report.xlsx');
I have not tested the code. So apologies if I made a mistake. You can refer to official documentation.
There are also other methods of exporting which you can find from the documentation.

you can do it by doing this way.
Step 1: in your controller
bind $request in Report-Export Class. add code in method where you are calling export excel.
return Excel::download(new ReportExport($request), 'report.xlsx');
step 2:
protected $request;
public function __construct($request)
{
$this->request = $request;
}
public function collection()
{
$request = $this->request ;
return User::where('customer_id',$request->cId)->get();
}

Related

Laravel Excel export

While exporting the data, it seemed to add the conditions for exporting. So, I made the constructor method and passed the data from the controller.
public function __construct($company_pan, $user_pan)
{
$this->company_pan = $company_pan;
$this->user_pan = $user_pan;
}
public function collection()
{
return PurchaseDetail::where([
['pan_code', $this->user_pan],
['s_pan', '=', $this->company_pan]
])->get();
}
In the Controller,
public function export(Request $request)
{
$company_pan = $request->pan;
$user_pan = Auth::user()->pan_code;
return Excel::download(new ConfirmationExport($company_pan, $user_pan), 'Confirmation.xlsx');
}
All the output is blank excel. But if I changed the code in the collection of s_pan as
public function collection()
{
return PurchaseDetail::where([
['pan_code', $this->user_pan],
['s_pan', '=', '303030333']
])->get();
}
It exports the data as expected. What actually the problem is?
Have you defined the attributes of your class? Like this?
<?php
namespace App\Exports;
use Maatwebsite\Excel\Concerns\FromCollection;
class ExampleExport implements FromCollection
{
protected $company_pan;
protected $user_pan;
public function __construct($company_pan, $user_pan)
{
$this->company_pan = $company_pan;
$this->user_pan = $user_pan;
}
public function collection()
{
return PurchaseDetail::where([
['pan_code', $this->user_pan],
['s_pan', '=', $this->company_pan]
])->get();
}
}

Export Excel in Laravel

**I have a problem with passing parameters on export file, I want to filter the export according to date selected on page. Hope you help me with this issue. Thanks **
This is my ExportController, I request data from form to my controller to give the export collection a date.
namespace App\Http\Controllers;
use Illuminate\Http\Response;
use Illuminate\Http\Request;
use App\Exports\ExportAttendance;
use Maatwebsite\Excel\Facades\Excel;
class ExportController extends Controller
{
public function export(Request $request)
{
return Excel::download(new ExportAttendance($request->input('min'),$request->input('max')),'Attendance.xlsx');
}
}
This is my ExportAttendance.php, this is responsible for the exportation of collections. On the query function I want to filter the data according on the date requested on the controller. How could I passed a data from controller to my Export.php, I did used constructors but it always return errors.
public function headings():array{
return[
'Name',
'In (AM)',
'Out (AM)',
'In (PM)',
'Out (PM)',
'Meeting',
'Task',
'Note',
'Total Hours',
'Date'
];
}
public function query()
{
$start = "2021-06-14";
$end = "2021-06-14";
return Attendance::select('Name','InAm','OutAM','InPM','OutPM','Meeting','SpecialTask','Undertime','TotalHours','Date')->whereBetween('Date',[$start,$end]);
}
public function collection()
{
return Attendance::all();
}
public function map($attendance):array
{
return[
$attendance->Name,
$attendance->InAM,
$attendance->OutAM,
$attendance->InPM,
$attendance->OutPM,
$attendance->Meeting,
$attendance->SpecialTask,
$attendance->Undertime,
$attendance->TotalHours,
$attendance->Date,
];
}
Instead of passing the $request object to the export class. You can simply use the request helper method.
public function query()
{
return Attendance::select('Name','InAm','OutAM','InPM','OutPM','Meeting','SpecialTask','Undertime','TotalHours','Date')
->whereBetween('Date',[request('start'), request('end')]);
}
Passing parameters is supposed to work too. Pls let me know what errors you see so I can update my answer.
I used Constructor
public function query()
{
$start = "2021-06-14";
$end = "2021-06-14";
return Attendance::select('Name','InAm','OutAM','InPM','OutPM','Meeting','SpecialTask','Undertime','TotalHours','Date')->where('Date','=',$this->year);
}
And this is my controller,
public function export(Request $request)
{
ob_start();
$datestart = $request->input('min');
$datestart = ob_get_contents();
return Excel::download(new ExportAttendance($datestart),'Attendance.xlsx');
ob_end_flush();
}
Another problem arise, when I used ob_end_clean() all my variable values returned nulls.

Getting specific value when using eloquent from Laravel

I am using Laravel 5.2 and I need to get specific values from the database with a leftjoin. The code I am using is as follow:
public function commentList(Request $request)
{
$inputs = $request->all();
$commentList = Comment::select(
'projects_comments.id as comment_id',
'u.name as user_name',
'projects_comments.comment as comment',
'projects_comments.created_at as created_at'
);
$commentList->leftjoin('users AS u', 'projects_comments.user_id', '=', 'u.id');
if (!empty($inputs['project_ids'])) {
$commentList->where(function ($query) use ($inputs) {
foreach ($inputs['project_ids'] as $i) {
$query->orWhere('projects_comments.project_id', $i);
}
});
};
$data = $commentList->get();
return $data;
}
It works fine but I would like to know if there is a better way to do this using eloquent but I can't really understand how to write this for eloquent to work. I need to get all the comments from an array of project ids.
I have the following model for Comment:
class Comment extends Model
{
protected $table = 'projects_comments';
public $timestamps = true;
protected $guarded = ['id'];
public function project()
{
return $this->belongsTo('App\Project', 'project_id');
}
public function user()
{
return $this->belongsTo('App\User', 'user_id');
}
}
I assume what you want is to get Comments (with their users) that belongs to specific Projects provided by the user as an array of IDS
Comment::whereIn('project_id', $inputs['project_ids'])->with('user')->get();
And if you only want the id and name of the user associated with the comment, pass the fields to the with function like so
Comment::whereIn('project_id', $inputs['project_ids'])
->with('user:id,name')->get();

Get onlyTrashed() does not exist in query builder

I am trying to get trashed rows from table messages:
public function trash() {
return $this->onlyTrashed()
->where('user_id', '=', $this->_u)
->orWhere('receiver', '=', $this->_u)
->orderBy('deleted_at', 'desc')->get();
}
I get this error:
Method Illuminate\Database\Query\Builder::onlyTrashed does not exist.
I checked up Builder and SoftDeletes files for onlyTrashed method and it does not exist, how can I look up to trashed messages from message table?
The only way I think about is to create method that doesn't return messages where delete_at is not null and for trashed to return only those where it is not null. But I am still wondering why this doesn't work since it is in documentation at this url:
https://laravel.com/docs/5.6/eloquent#soft-deleting
MORE INFO
Yes it is inside model and yes I added use SoftDeletes:
use Illuminate\Database\Eloquent\SoftDeletes; - on top
use SoftDeletes; after opening the class
Let me paste entire model here:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;
class Messages extends Model
{
use SoftDeletes;
protected $fillable = [
'user_id', 'subject', 'text', 'receiver'
];
public $_u;
protected $dates = ['deleted_at'];
public function __construct() {
$this->_u = auth()->user()->user_id; //or some id as string
}
public function trash() {
return $this->onlyTrashed()
->where('user_id', '=', $this->_u)
->orWhere('receiver', '=', $this->_u)
->orderBy('deleted_at', 'desc')->get();
}
public static function trashed() {
return self::onlyTrashed();
}
}
And controller has:
public function __construct() {
$this->middleware('auth');
}
public function index($field = 'trash') {
if ($field !== "new") {
$messages = (new Msg)->$field();
$user = auth()->user();
return view('pages.messages', compact('messages', 'user'));
}
return view('pages.messages.new', compact('messages', 'user'));
}
I tried calling static as well and I tried doing it from tinker and still keep getting:
onlyTrashed() doesn not exist
You have to call the parent constructor:
public function __construct() {
parent::__construct();
$this->_u = auth()->user()->user_id;
}
I think what you want is to define the trash method static:
public static function trash() {
return self::onlyTrashed()
->where('user_id', '=', $this->_u)
->orWhere('receiver', '=', $this->_u)
->orderBy('deleted_at', 'desc')->get();
}
Then call this function by:
$messages = Messages::trash();
This should work
# YourModelController.php
/**
* Show only trashed
*
* #return \Illuminate\Http\Response
*/
public function trashed()
{
...
$trashed = YourModel::onlyTrashed()->get();
...
}
I have researched a little further and I got this:
From https://laravel.com/api/5.6/Illuminate/Database/Eloquent.html
I should have
SoftDeletesTrait
but I have
SoftDeletes
. In softdeletestrait we have onlyTrashed method but in SoftDeletes we do not.
So I copied that method from this page:
https://github.com/laravel/framework/blob/7d9e7068c49f945385673014d4cba4de28accd5e/src/Illuminate/Database/Eloquent/SoftDeletingTrait.php#L119
And added it to SoftDeletes class, now it works like it should. I haven't find why it doesn't exist inside SoftDeletes class so if anyone find out let us know!

Laravel : Call to undefined method Illuminate\\Database\\Query\\Builder

On query get the error with undefine method. Simply i want to get data from two tables query look linke
public static function userDetail($id){
$result = User::whereHas('user_details', function ($query) {
$query->where('user_details.user_id',$id);
})->first();
return $result ;
}
Relationship
On Model User define relationship
public function userDetails()
{
return $this->hasOne(UserDetails::class);
}
and in userDetails model
public function user()
{
return $this->belongsTo(User::class);
}
just change
public static function userDetail($id){
$result = User::whereHas('user_details', function ($query) use($id) {
$query->where('user_id',$id);
})->first();
return $result ;
}
If you dont need to use static, you can use this $result value on userDetails
public function userDetail($id){
$result = userDetails::where('user_id', '=', $id)->first();
return $result ;
}
Then the result can get access to the user from the vale by using $value->user->{user property}

Resources