I am beginner webdeveloper,
I use in my project Laravel 7 and maatwebsite/excel
I have this code:
namespace App\Models;
use App\Models\Reservation;
use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\Exportable;
class ReservationExport implements FromCollection, WithHeadings
{
use Exportable;
protected $date;
public function __construct(string $date)
{
$this->date = $date;
}
public function headings(): array
{
return [
'LP',
'ID Rezerwacji',
'Adres email',
'Token',
'Data',
'Godzina',
'Tor',
'Płeć',
];
}
public function collection()
{
$res = Reservation::select('id', 'id', 'email', 'token', 'date', 'hour', 'track', 'sex')->where('date', $this->date)->orderBy('time', 'ASC')->orderBy('track', 'ASC')->get();
foreach ($res as $val) {
$val->sex = ($val->sex == 1) ? 'kobieta' : 'mężczyzna';
}
return $res;
}
}
public function export(Request $request)
{
return Excel::download(new ReservationExport($request->input('query')), 'reservation-'.$request->input('query').'.xlsx');
}
This code generates an Excel document. It works fine. I would like to add a sequence number in 1 column (1,2,3 etc).
How can I do this?
My model:
class Reservation extends Model
{
protected $quarded = ['id'];
protected $fillable = ['email', 'token', 'date', 'hour', 'track', 'sex', 'time', 'people'];
public $timestamps = true;
protected $table = 'reservations';
}
Please help
try this
basically u need to add sn to heading then in your collection u need to a new key sn with calculated sequence number
hope it will work if not please tell me what error u r getting
<?php
use App\Models\Reservation;
use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\Exportable;
class ReservationExport implements FromCollection, WithHeadings
{
use Exportable;
protected $date;
public function __construct(string $date)
{
$this->date = $date;
}
public function headings(): array
{
return [
'SN', // sn new key adding
'LP',
'ID Rezerwacji',
'Adres email',
'Token',
'Data',
'Godzina',
'Tor',
'Płeć',
];
}
public function collection()
{
$res = Reservation::select('id', 'id', 'email', 'token', 'date', 'hour', 'track', 'sex')->where('date', $this->date)->orderBy('time', 'ASC')->orderBy('track', 'ASC')->get();
foreach ($res as $val) {
$val->sex = ($val->sex == 1) ? 'kobieta' : 'mężczyzna';
}
$res->map(function ($row,$key) {
return $row['sn'] = $key; // sn key added to collection
});
return $res;
}
}
Related
This is my controller:
public function index($mid,$payload){
$search = $payload['search'];
$users = DB::select('SELECT a.id, a.alternate_id, a.setujuterma, a.mykad, a.nama, a.email, a.notel, a.etunai,
b.ranktitle, c.ranktitle AS appointed_rank, d.nama as hirarki, e.alternate_id as placement,
e.nama as leadername, a.akses, a.suspendreason, a.regstamp,
a.matagajet, f.display as hirarkidisplay, IF(a.mykadverify = "3","1","0") as mykadverifydecode
FROM pengguna as a
LEFT JOIN penggunarank b ON a.effective_rank = b.id
LEFT JOIN penggunarank c ON a.appointed_rank = c.id
LEFT JOIN hirarki d ON a.userrank = d.id
LEFT JOIN pengguna e ON a.placement = e.id
LEFT JOIN hirarkimid f ON a.userrank = f.hirarki AND a.mid = f.mid
WHERE a.mid ='. $mid .' AND a.akses != -1'
);
$sortUser = collect($users)->sortByDesc('alternate_id')->toArray();
$collection = collect($sortUser);
$count = count($users);
// SEARCH BOX
if ($search) {
$collection->where(function ($q) use ($search) {
$q->where("alternate_id","LIKE","%{$search}%")
->orWhere("nama","LIKE","%{$search}%")
->orWhere("mykad","LIKE","%{$search}%")
->orWhere("notel","LIKE","%{$search}%")
->orWhere("email","LIKE","%{$search}%");
});
}
return [
$user,
$count
];
}
So,
$users return an array.
$collection return collection
for the search box, if I use $users, I get error
"Call to a member function where() on Array"
and if I use $collection, I get
message: "explode() expects parameter 2 to be string, object given", exception: "ErrorException",…}
Any help would be greatly appreciated. Thanks.
public function search(Request $payload){
$search = $payload['search'];
if($search == "")
{
$users = Payee::whereNotNull('payee_name')->take(10)->get();
}
else
{
$users = Payee::whereNotNull('payee_name')
->where(function ($q) use ($search) {
$q->where("payee_name","LIKE","%$search%")
->orWhere("payee_nick_name","LIKE","%$search%");
})->take(10)->get();
}
return [
$users,
];
}
I found an answer to my question. All I need is to change the query into eloquent model class. There is no other way if I want to use the where() function for my search. First I create model User.php:
<?php
namespace App;
use App\WithdrawEcash;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Propaganistas\LaravelPhone\PhoneNumber;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use HasApiTokens, Notifiable, HasFactory;
protected $table = 'pengguna';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $guarded = ['id'];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
// user registered by
public function userRegby()
{
return $this->belongsTo(User::class, 'regby');
}
// user leader
public function userPlacement()
{
return $this->belongsTo(User::class, 'placement');
}
public function penggunaRank()
{
return $this->belongsTo(PenggunaRank::class, 'effective_rank');
}
public function appointedRankUser()
{
return $this->belongsTo(PenggunaRank::class, 'appointed_rank');
}
public function penyatabonus()
{
return $this->belongsTo(User::class, 'id', 'pengguna');
}
//Hirarkimid userrank
public function userHirarki()
{
return $this->belongsTo(Hirarkimid::class, 'userrank', 'hirarki');
}
public function userhirarchy()
{
return $this->belongsTo(Hierarchy::class, 'userrank')->select('id', 'nama');
}
public function systemHirarki()
{
return $this->belongsTo(Hierarchy::class, 'userrank');
}
// user order
public function userOrders()
{
return $this->hasMany(Order::class, 'pengguna');
}
// user order for registration report
public function userOrder()
{
return $this->hasOne(Order::class, 'pengguna');
}
public function hierarchy()
{
$hirarki = $this->belongsTo(Hirarkimid::class, 'userrank', 'hirarki')
->select('hirarki', 'display', 'shownilaibelian', 'show_harga_ketika_pesanan')
->where('mid', auth()->user()->mid);
if ($hirarki) {
return $hirarki;
} else {
return $this->belongsTo(Hierarchy::class, 'userrank')->select('id', 'nama');
}
}
public function myCartLists()
{
return $this->hasMany(AddToCart::class, 'user_id');
}
public function bonusStatement()
{
return $this->hasMany(PenyataBonus::class, 'pengguna');
}
public function currentBonusStatement()
{
return $this->hasMany(PenyataBulanSemasa::class, 'pengguna');
}
public function withdrawEcash()
{
return $this->hasMany(WithdrawEcash::class, 'pengguna');
}
public function fileupload()
{
return $this->morphOne(FileUpload::class, 'file_upload');
}
public function fileuploads()
{
return $this->morphMany(FileUpload::class, 'file_upload');
}
public function voucherdetail()
{
return $this->hasMany(Voucherdetail::class, 'pengguna');
}
public function countryCode()
{
return $this->hasOne(Negara::class, 'nama', 'negara')->value('kod');
}
public function setNotelAttribute($value)
{
if (!is_null($value)) {
$country_code = $this->countryCode() != '' ? $this->countryCode() : 'MY';
$this->attributes['notel'] = PhoneNumber::make($value, $country_code)
->formatForMobileDialingInCountry($country_code);
} else
$this->attributes['notel'] = $value;
}
public function setNotelcsAttribute($value)
{
if (!is_null($value)) {
$country_code = $this->countryCode() != '' ? $this->countryCode() : 'MY';
$this->attributes['notelcs'] = PhoneNumber::make($value, $country_code)
->formatForMobileDialingInCountry($country_code);
} else
$this->attributes['notelcs'] = $value;
}
}
And in my controller I simply call the user model:
$user = User::query()->select('id', 'alternate_id', 'setujuterma', 'mykad', 'nama', 'email', 'notel', 'etunai',
'effective_rank','appointed_rank', 'akses', 'suspendreason', 'regstamp',
'matagajet', 'userrank','mykadverify','placement')
->with([
'penggunaRank' => function($q) use ($mid){
$q->select('id','ranktitle')->where('mid',$mid);
},
'appointedRankUser' => function($q) use ($mid){
$q->select('id','ranktitle')->where('mid',$mid);
},
'systemHirarki'=> function($q){
$q->select('id', 'nama');
},
'userHirarki' => function($q) use ($mid){
$q->select('hirarki','display')->where('mid',$mid);
},
'userPlacement' => function($q){
$q->select('id','alternate_id','nama');
}
])
->where('mid',$mid)
->where('akses','!=',-1);
if ($search) {
$user->where(function($q) use ($search){
$q->where("alternate_id","LIKE","%{$search}%")
->orWhere("nama","LIKE","%{$search}%")
->orWhere("mykad","LIKE","%{$search}%")
->orWhere("notel","LIKE","%{$search}%")
->orWhere("email","LIKE","%{$search}%");
});
}
return $user->orderBy('alternate_id','desc')
Hope everyone can get benefits from this. Thank you.
This is my first time using Maatweb/Excel in Laravel 7
The excel file is downloaded but it is empty.
I dont know what is wrong with this. Maybe some one can help me.
Here is my code AdsExport.php:
<?php
declare(strict_types=1);
namespace App\Exports;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithHeadings;
class AdsExport implements WithHeadings
{
/**
* #return \Illuminate\Support\Collection
*/
use Exportable;
private $dateFrom;
private $dateTo;
public function __construct(string $dateFrom, string $dateTo)
{
$this->dateFrom = $dateFrom;
$this->dateTo = $dateTo;
}
public function headings(): array
{
return ['View', 'Clicks', 'URL', 'Company Name', 'Ad Title'];
}
public function query()
{
return DB::table('ads_management')
->select(DB::raw('select COUNT(ad_views.id) as count_views from ad_views left join
ads_management on ads_management.id = view_ads.ads_id where ad_views.created_by between ? and ?'),
DB::raw('select COUNT(ad_clicks.id) as count_clicks from ad_clicks left join
ads_management on ads_management.id = view_clicks.ads_id where ad_clicks.created_by between ? and ?'), 'ad_link', 'company_name', 'title')
->setBindings([$this->dateFrom, $this->dateTo, $this->dateFrom, $this->dateTo])
->get();
}
}
Thanks in advance
I have four tables:
Agroindustria
Pessoa
PessoaJuridica
Endereco
. Here are their Models:
Agroindustria
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Agroindustria extends Model
{
use SoftDeletes;
protected $table = "agroindustria";
protected $primaryKey = "CodAgroindustria";
public $incrementing = false;
protected $keyType = 'string';
public $fillable = ['CodAgroindustria, Porte'];
public $hidden = ['created_at', 'updated_at', 'deleted_at'];
public function pessoa () {
return $this->setConnection('diana')->hasOne(Pessoa::class, 'CodPessoa', 'CodAgroindustria');
}
public function pessoajuridica()
{
return $this->setConnection('diana')->hasOne(PessoaJuridica::class, 'CodPessoa', 'CodEndereco');
}
public function endereco()
{
return $this->setConnection('diana')->hasOne(PessoaJuridica::class, 'CodEndereco', 'CodEndereco');
}
public function estado(){
return $this->setConnection('diana')->hasOne(Estado::class, 'CodEstado', 'estado');
}
public function cidade(){
return $this->setConnection('diana')->hasOne(Cidade::class, 'CodCidade', 'cidade');
}
}
Pessoa:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Pessoa extends Model
{
// use SoftDeletes;
protected $table = "pessoa";
protected $primaryKey = "CodPessoa";
public $incrementing = false;
protected $keyType = 'string';
protected $connection = "diana";
public $hidden = ['created_at', 'updated_at', 'EXCLUIDO', 'LastSend'];
public $fillable = ['email', 'TelRes', 'TelCel'];
public function endereco()
{
return $this->hasOne('App\Endereco', 'CodEndereco', 'CodEndereco');
}
public function pessoafisica()
{
return $this->hasOne('App\PessoaFisica', 'CodPessoaFisica', 'CodPessoa');
}
public function pessoajuridica()
{
return $this->hasOne('App\PessoaJuridica', 'CodPessoaJuridica', 'CodPessoa');
}
}
The PessoaJuridica and Endereco Models are pretty much the same as the Pessoa Model.
When I soft delete my Agroindustria, the deleted_at column updates successfully, but I'm struggling with updating the EXCLUIDO column values from 0 to 1 in my other models.
Here's the delete function I created in my AgroindustriaController:
public function deletar (Request $request)
{
try {
$Agroindustria = Agroindustria::where('CodAgroindustria', $request['CodAgroindustria']);
$Agroindustria->delete();
$Pessoa = Pessoa::findOrFail($request['CodPessoa']);
if ($Agroindustria->delete()) {
DB::table('Pessoa')->where('CodPessoa', $Pessoa->CodPessoa)
->update(array('EXCLUIDO' => 1));
}
return response()->json([
'error' => false,
'data' => [
'message' => 'Dados deletados com sucesso',
]
]);
} catch (Exception $e) {
return response()->json([
'error' => true,
'message' => [$e->getMessage()]
]);
}
}
second line in try
$Agroindustria->delete();
write this line like this
$dlt = $Agroindustria->delete();
after that in your if condition put this variable $dlt like this
if ($dlt) {
DB::table('Pessoa')->where('CodPessoa', $Pessoa->CodPessoa)
->update(array('EXCLUIDO' => 1));
}
Solved it by doing:
$Agroindustria = Agroindustria::where('CodAgroindustria', $request['CodAgroindustria']);
$dlt = $Agroindustria->delete();
if ($dlt) {
Pessoa::where('CodPessoa', $request['CodPessoa'])
->update(array('EXCLUIDO' => 1));
PessoaJuridica::where('CodPessoaJuridica', $request['CodPessoaJuridica'])
->update(array('EXCLUIDO' => 1));
Endereco::where('CodEndereco', $request['CodEndereco'])
->update(array('EXCLUIDO' => 1));
}
Thank you all!
I am generating a Excel Export, I want to change the timestamps format in excel file from 2020-07-29 13:56:09 to just DD:MM:YYYY.
How can I change my Export Class to Format the timestamp Column in my Excel File, BTW Date is in 'E' column in Excel file.
My Export Class:
use App\outbound_detail;
use App\outbound_temp;
use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\FromView;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Events\AfterSheet;
class ReleaseExportView implements FromCollection, WithHeadings, ShouldAutoSize, WithEvents
{
protected $reference;
function __construct($reference)
{
$this->reference = $reference;
}
public function collection()
{
return outbound_detail::where('reference', $this->reference)->get([
'reference', 'sku_parent', 'sku_child', 'cases', 'updated_at'
]);
}
public function headings(): array
{
return [
'Reference',
'SKU Parent',
'SKU Child',
'Cases Released',
'Date Created'
];
}
// ...
/**
* #return array
*/
public function registerEvents(): array
{
return [
AfterSheet::class => function (AfterSheet $event) {
$cellRange = 'A1:W1'; // All headers
$event->sheet->getDelegate()->getStyle($cellRange)->getFont()->setSize(14);
},
];
}
}
On your Reference Model, add this :
public function getUpdatedAtAttribute($date)
{
return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('d:m:Y');
}
You can use it's column formatting.
Try this:
// ...
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
class ReleaseExportView implements FromCollection, WithHeadings, ShouldAutoSize, WithEvents, WithColumnFormatting
{
// ...
public function map($reference): array
{
return [
$reference->reference,
$reference->sku_parent,
$reference->sku_child,
$reference->cases,
Date::dateTimeToExcel($reference->updated_at)
];
}
public function columnFormats(): array
{
return [
'E' => NumberFormat::FORMAT_DATE_DDMMYYYY
];
}
}
I am working in Laravel, and I have a model Group where I have rules for validation. I am attempting to have a unique name_group but only for the given year. The code below works perfectly if I replace .$this->year_groups with 2016 for example. But when I try to add the actual year of the group to be created by concatenating .this->year_groups, I get a syntax error:
Symfony \ Component \ Debug \ Exception \ FatalErrorException syntax error, unexpected '.', expecting ')'
I have looked at many examples and they (seem) to be written this way, and I just can't find what is wrong. I am thinking perhaps it has something to do that this is in an array...?
Any help would be greatly appreciated!!
Model:
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class Group extends Eloquent implements UserInterface,RemindableInterface
{
use UserTrait, RemindableTrait;
protected $table = 'groups';
protected $primaryKey = "id_groups";
protected $fillable = array('name_groups','year_groups','grados_id_grados');
//The error is in the following $rules
public static $rules = array(
'year_groups'=> 'required',
'name_groups'=> 'required|unique:groups,name_groups,NULL, id_groups,year_groups,' . $this->year_groups,
'grados_id_grados' => 'required'
);
public function grado()
{
return $this->belongsTo('Grado','grados_id_grados');
}
public function students()
{
return $this->belongsToMany('Student','group_student','id_group','id_student')->withTimestamps();
}
public function teachers()
{
return $this->belongsToMany('Teacher','group_subject_teacher','id_group','id_teacher')->withPivot('id_subject','year_groups')->withTimestamps();
}
}
In the Controller I call validation from the store method:
public function store()
{
$input = Input::all();
$validation = Validator::make($input, Group::$rules);
if($validation->passes()){
$group = new Group;
$group->name_groups = Input::get('name_groups');
$group->year_groups = Input::get('year_groups');
$group->grados_id_grados = Input::get('grados_id_grados');
$group->save();
}
}
Looking your code, it seems $rules is variable or property of class. The way you are assigning values to property are wrong, so it is throwing error. Look below code and arrange your code accordingly:-
class anyClass {
private $year_groups = "2016";
public $rules = [];
public function __construct(){
$this->rules = array(
'year_groups'=> 'required',
'name_groups'=> 'required|unique:groups,name_groups,NULL, id_groups,year_groups,'.$this->year_groups,
'grados_id_grados' => 'required'
);
}
}
I changed Model to:
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class Group extends Eloquent implements UserInterface,RemindableInterface
{
use UserTrait, RemindableTrait;
protected $table = 'groups';
protected $primaryKey = "id_groups";
protected $fillable = array('name_groups','year_groups','grados_id_grados');
//This part I changed
public static $rules = [];
public static function _construct($year){
$rules = array(
'year_groups'=> 'required',
'name_groups'=> 'required|unique:groups,name_groups,NULL, id_groups,year_groups,' . $year,
'grados_id_grados' => 'required'
);
return $rules;
}
public function grado()
{
return $this->belongsTo('Grado','grados_id_grados');
}
public function students()
{
return $this->belongsToMany('Student','group_student','id_group','id_student')->withTimestamps();
}
public function teachers()
{
return $this->belongsToMany('Teacher','group_subject_teacher','id_group','id_teacher')->withPivot('id_subject','year_groups')->withTimestamps();
}
}
Then in Controller:
public function store()
{
$input = Input::all();
$validation = Validator::make($input, Group::_construct(Input::get('year_groups')));
if($validation->passes()){
$group = new Group;
$group->name_groups = Input::get('name_groups');
$group->year_groups = Input::get('year_groups');
$group->grados_id_grados = Input::get('grados_id_grados');
$group->save();
}
}