I'm having a really strange issue here. I have a user model (detailed below).
It all works fine until I added the getReportsSharedAttribute function. When this is added, the server freezes and I get:
PHP Fatal error: Maximum execution time of 60 seconds exceeded in C:\Users\User\PhpstormProjects\laravel-vue\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\HasRelationships.php on line 637
more:
exception: "Symfony\\Component\\ErrorHandler\\Error\\FatalError"
file: "C:\\Users\\User\\PhpstormProjects\\laravel-vue\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Eloquent\\Concerns\\HasAttributes.php"
I thought there was something up with the code, so I ran it manually in a controller and dumped it, it worked fine.
So I tried it as a relation instead of an attribute. Same error.
So then I thought, is it just specific to the ReportingSetAssigned model, so I did another query on another collection, and another, and I still get the timeout error.
I tried another Model, it worked fine, for no apparent reason. Even though there were a lot more records inside. It doesn't seem to be dependant on how many columns are involved in the return. None of my tables have more than 50 records inside, even in the relations.
What's going on here? Is there some limit somewhere?
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Query\Builder;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\DB;
use Laravel\Sanctum\HasApiTokens;
use stdClass;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable, SoftDeletes;
public $appends = [
'full_name',
'profile_photo_thumb',
'permissions_alt',
'line_managed_only_id',
'line_managers_only_id',
'permissions_meetings_only_id',
'reports_shared',
];
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
protected $dates = ['deleted_at'];
public function permissions(){
return $this->belongsToMany(Permission::class);
}
public function timelineitems(){
return $this->hasMany(TimelineItem::class);
}
public function line_managers(){
return $this->belongsToMany(User::class,'permissions_lm','user_id','lm_id');
}
public function line_managed(){
return $this->belongsToMany(User::class,'permissions_lm','lm_id','user_id');
}
public function permissions_meetings(){
return $this->belongsToMany(Area::class,'permissions_meetings','user_id','area_id')->withPivot('level');
}
public function getPermissionsMeetingsOnlyIdAttribute(){
return $this->permissions_meetings()->pluck('permissions_meetings.area_id');
}
public function permissions_qed(){
return $this->belongsToMany(Area::class,'permissions_qed','user_id','area_id')->withPivot('level');
}
public function permissions_reporting(){
return $this->belongsToMany(Area::class,'permissions_reporting','user_id','area_id')->withPivot('level');
}
public function permissions_reporting_sets(){
return $this->belongsToMany(ReportingSet::class,'permissions_reporting_sets','user_id','set_id')->withPivot('level');
}
public function improvement_category_objective_action_milestones(){
return $this->belongsToMany(ImprovementSetCategoryObjectiveActionMilestone::class);
}
public function planning_review_forms(){
return $this->hasMany(PerformanceManagementSetAssigned::class)->whereHas('set', function($q) {
$q->where('appraisal', 0);
});
}
public function appraisal_forms(){
return $this->hasMany(PerformanceManagementSetAssigned::class)->whereHas('set', function($q) {
$q->where('appraisal', 1);
});
}
public function performance_manager_set_as_lm(){
return $this->belongsTo(PerformanceManagementSetAssigned::class, 'lm_id');
}
public function getPermissionsAttribute(){
return $this->permissions()->get();
}
public function getLineManagersOnlyIdAttribute(){
return $this->line_managers()->pluck('permissions_lm.lm_id');
}
public function getLineManagedOnlyIdAttribute(){
return $this->line_managed()->pluck('permissions_lm.user_id');
}
public function hasPermissionTo($permission){
if(auth()->user()->super_admin){
return true;
}
if($permission==='super_admin'&&auth()->user()->super_admin){
return true;
}
if(!is_array($permission)){
$access = $this->permissions()->where('permission', $permission)->exists();
if($access){
return true;
}
return false;
}else{
foreach($permission as $p){
$access = $this->permissions()->where('permission', $permission)->exists();
if($access){
return true;
}
}
}
}
public function checkPermissionReportingSet($permission){
$access = $this->permissions_reporting_sets()->where('set_id', $permission)->first();
if($access){
if($access->pivot->level=='read'){
return 'read';
}
if($access->pivot->level=='write'){
return 'write';
}
}
}
public function checkPermissionReportingArea($permission){
$access = $this->permissions_reporting()->where('area_id', $permission)->first();
if($access){
if($access->pivot->level=='true'){
return true;
}
}
}
public function truePermission($permission){
$access = $this->permissions()->where('permission', $permission)->exists();
if($access){
return true;
}
}
public function updateTimeline($type_main,$type_sub,$title,$content,$icon,$color,$link,$relevant_id = null,$user_id = null){
if(!$user_id){
$user_id = $this->id;
}
$t = new TimelineItem();
$t->type_main = $type_main;
$t->type_sub = $type_sub;
$t->title = $title;
$t->content = $content;
$t->icon = $icon;
$t->color = $color;
$t->link = $link;
$t->user_id = $user_id;
$t->relevant_id = $relevant_id;
$t->save();
}
public function getPermissionsForVueAttribute(){
$permissions = $this->permissions;
$new = [];
foreach($permissions as $p){
$new[$p->permission] = true;
}
$new['meeting_areas'] = [];
$permissions = $this->permissions_meetings;
foreach($permissions as $p){
$new['meeting_areas'][$p->id] = $p->pivot->level;
}
$new['qed_areas'] = [];
$permissions = $this->permissions_qed;
foreach($permissions as $p){
$new['qed_areas'][$p->id] = $p->pivot->level;
}
$new['reporting_areas'] = [];
$permissions = $this->permissions_reporting;
foreach($permissions as $p){
$new['reporting_areas'][$p->id] = $p->pivot->level;
}
$new['reporting_sets'] = [];
$permissions = $this->permissions_reporting_sets;
foreach($permissions as $p){
$new['reporting_sets'][$p->id] = $p->pivot->level;
}
return json_encode($new);
}
public function getPermissionsAltAttribute(){
//General permissions
$permissions = Permission::get();
$newP = [];
foreach($permissions as $p){
$newP[$p->permission] = false;
}
$permissions = $this->permissions;
foreach($permissions as $p){
$newP[$p->permission] = true;
}
$newP['meeting_areas'] = [];
$newP['qed_areas'] = [];
$newP['reporting_areas'] = [];
$newP['reporting_sets'] = [];
foreach(Area::orderBy('name', 'ASC')->get() as $p){
$newP['meeting_areas'][$p->id] = "false";
$newP['qed_areas'][$p->id] = "false";
$newP['reporting_areas'][$p->id] = "false";
}
$meetings = DB::table('permissions_meetings')->where('user_id', '=', $this->id)->get();
foreach($meetings as $p){
$newP['meeting_areas'][$p->area_id] = $p->level;
}
$qed = DB::table('permissions_qed')->where('user_id', '=', $this->id)->get();
foreach($qed as $p){
$newP['qed_areas'][$p->area_id] = $p->level;
}
$reporting = DB::table('permissions_reporting')->where('user_id', '=', $this->id)->get();
foreach($reporting as $p){
$newP['reporting_areas'][$p->area_id] = $p->level;
}
foreach(ReportingSet::orderBy('name', 'ASC')->get() as $p){
$newP['reporting_sets'][$p->id] = "false";
}
$reporting = DB::table('permissions_reporting_sets')->where('user_id', '=', $this->id)->get();
foreach($reporting as $p){
$newP['reporting_sets'][$p->set_id] = $p->level;
}
return $newP;
}
public function getCyclesAttribute(){
return Cycle::orderBy('id')->get();
}
public function getFullNameAttribute(){
return $this->first_name . " " . $this->last_name;
}
public function getProfilePhotoThumbAttribute(){
if($this->profile_photo){ return "THUMB-" . $this->profile_photo; }else{ return "no-avatar.png"; }
}
public function getReportsSharedAttribute(){
return ReportingSet::where('observee_id', $this->id)->where('observee_share', 1)->where('published', 1)->without('set.modules')->get()->toArray();
}
public function canLineManage($id){
if($this->super_admin==1) return true;
foreach($this->line_managed as $lm){
if($lm->id==$id){
return true;
}
}
}
}
EDIT: If I run this code in a controller, it does't hang at all. It loads up the data in less than a second
EDIT: Restarted computer, still happening
This looks a lot like an infinitive call-loop, please refer to this on github issue
Allowed Memory size exhaused when accessing undefined index in toArray
You are just running out of memory when calling parent::toArray(). You
either need to reduce the amount of items in your collection or
increase your allowed memory allocation.
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.
[SOLVED]
/***
The parent-children relationship works fine. But there was a code i wrote several weeks ago that prevent me to update the progress value.
***/
I have a project that has similar functionality to trello (kanban)
There are 3 models which are projects, TaskList (columns), Tasks (cards).
a project has many columns
a column has many tasks
a task has many
subtasks (the subtask refer to the model itself)
each model has a column named progress. This column must be updated when the children are updated. The progress is calculated by averaging the progress of all cards.
Models :
Project.php
class Project extends Model
{
use HasFactory;
protected $table = 'projects';
public $timestamps = true;
protected $fillable = [
'id','title', 'description', 'actual_start', 'actual_end',
'start', 'end','progress'
];
public function updateProgress(){
$sum=0;
if(count($this->columns)){
for ($i = 0; $i < count($this->columns); $i++) {
$list = $this->columns[$i];
if($list->progress==null){
$list->progress=0;
}
$sum+=$list->progress;
}
$progress=$sum/count($this->columns);
$this->progress=round($progress);
$this->save();
}
return $this->progress;
}
public function scopeExclude($query, $value = [])
{
return $query->select(array_diff($this->fillable, (array) $value));
}
public function lists(){
return $this->hasMany(TaskList::class,'projects_id');
}
TaskList.php
class TaskList extends Model
{
protected $table = 'lists';
protected $fillable = [ 'title', 'position', 'projects_id', 'start', 'end', 'actual_start', 'actual_end','progress' ];
public static function boot() {
parent::boot();
static::saved(function($list){
$list->project->updateProgress();
});
}
public function updateProgress(){
$tes=[];
if(count($this->cards)){
$sum=0;
for ($i = 0; $i < count($this->cards); $i++) {
$task = $this->cards[$i];
if($task->progress==null){
$task->progress=0;
}
$sum+=$task->progress;
$tes[]=['id'=>$task->id,'progress'=>$task->progress,$task->cards];
}
$progress=$sum/count($this->cards);
$this->progress=round($progress);
$this->save();
}
return ['id'=>$this->id,'progress'=>$this->progress,'cards'=>$this->cards];
}
public function cards(){
return $this->hasMany(Task::class,'lists_id');
}
}
Task.php
class Task extends Model
{
use HasFactory;
protected $table = 'tasks';
public $timestamps = true;
protected $fillable = [
'id','users_id', 'title', 'description', 'complete', 'end', 'start',
'actual_start', 'actual_end', 'start_label', 'end_label',
'progress', 'is_subtask', 'lists_id','parent_task_id'
];
protected $casts = [
'progress' => 'double',
];
public static function boot() {
parent::boot();
static::saving(function($task){
if(!empty($task->start) && !empty($task->end)){
$start = Carbon::parse($task->start);
$end = Carbon::parse($task->end);
$days= $start->diffInDays($end);
$task->days=$days+1;
}
if(!empty($task->actual_start) && !empty($task->actual_end)){
$actual_start = Carbon::parse($task->actual_start);
$actual_end = Carbon::parse($task->actual_end);
$work_days= $actual_start->diffInDays($actual_end);
$task->work_days=$work_days+1;
}
// This part was the problem
if($task->parentTask){
if($task->actual_end){
$task->progress=100;
}else{
$task->progress=0;
}
}else{
if($task->actual_end){
$task->progress=100;
}else{
$task->progress=0;
}
}
if($task->parentTask){
if($task->actual_end){
$task->progress=100;
}else{
$task->progress=0;
}
}else{
if($task->actual_end){
$task->progress=100;
}else{
$task->progress=0;
}
}
//------------------------
if($task->progress==100){
$task->complete=true;
}
});
static::saved(function($task){
//is a subtask
if($task->parentTask){
// dd('subtask',$task->id,$task->complete,$task->progress,$task->parentTask,$task->list);
$task->parentTask->updateProgress();
}else{
// dd('parent task',$task->id,$task->complete,$task->progress,$task->parentTask,$task->list);
$task->list->updateProgress();
// dd('list ',$task->list->updateProgress());
}
});
static::deleting(function($task) {
foreach ($task->members as $i => $member) {
$member->delete();
}
foreach ($task->cards as $k => $subtask) {
$subtask->delete();
}
$task->tags()->detach();
$task->task_members()->detach();
});
}
public function updateProgress(){
if(count($this->cards)){
$valuePerSubtask=100/count($this->cards);
$completeSubtaskCounter=0;
for ($i = 0; $i < count($this->cards); $i++) {
$subtask = $this->cards[$i];
if($subtask->complete){
$completeSubtaskCounter++;
}
}
$progress=$completeSubtaskCounter*$valuePerSubtask;
$this->progress=$progress;
$this->save();
return [$this->progress,$progress];
}
}
public function scopeExclude($query, $value = [])
{
return $query->select(array_diff($this->fillable, (array) $value));
}
public function parentTask(){
return $this->belongsTo(Task::class,'parent_task_id');
}
public function list(){
return $this->belongsTo(TaskList::class,'lists_id');
}
}
I can't update the parent task from the children. As you can see in Task.php model, I have a updateProgress() that return [$this->progress, $progress]; after i call $this->save(). I already have $this->progress=$progress before i save it. But $this->progress still show the same result.
[![the first item is $this->progress, the second one is $progress][1]][1]
[1]: https://i.stack.imgur.com/RS2mq.png
i tried override touch() and place updateProgress() inside it. But still doesn't show the expected result.
Any advice for a better approach?
Am I missing something?
A solution also could be:
Create an observer on task.
php artisan make:observer TaskObserver
and then in the observer.
class UserObserver
{
//SOME METHODS
public function updated(Task $task)
{
/* Important, this will be done with all tasks on update in the tree
like Task->task->task etc... unless you put some extra logic. But
this is the general idea
*/
#search if parent
if ($task->parent_task_id !== null) {
//run progress
$task->parentTask->updateProgress()
}
}
}
I am using laravel 5.8 for my project, and i am getting the error Bad call Call to undefined method Illuminate\Database\Eloquent\Builder::withSum() because I removed LaravelSubQueryTrait in my traits. When i re-add LaravelSubQueryTrait, my project does not run, I am getting this error Trait method newBaseQueryBuilder has not been applied, because there are collisions with other trait methods on App\Traits\TestModelTrait. Upgrading to laravel 8.x is not an option at this point and I don't quite understand what I am doing wrong. Any tips/advise/ resources to read will be highly appreciated to help solve my problem. Thanks
My TestmodelTrait is as below :
use Alexmg86\LaravelSubQuery\Traits\LaravelSubQueryTrait;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;
use Watson\Rememberable\Rememberable;
trait MedyqModelTrait
{
protected static $skipUuid = false;
use MedyqTrait, SoftDeletes, Rememberable, LaravelSubQueryTrait;
protected static function boot()
{
parent::boot();
self::creating(function ($record) {
if (!self::$skipUuid) {
$record->{'uuid'} = (string)Str::orderedUuid();
}
if (auth()->check()) {
$record->{'created_by'} = auth()->id();
$record->{'updated_by'} = auth()->id();
}
});
self::updating(function ($record) {
if (auth()->check()) {
$record->{'updated_by'} = auth()->id();
}
});
self::updated(function ($record) {
$record->flushCache();
});
self::deleted(function ($record) {
if (auth()->check()) {
$record->{'deleted_by'} = auth()->id();
$record->save();
}
});
self::restored(function ($record) {
if (auth()->check()) {
$record->{'restored_by'} = auth()->id();
$record->{'restored_at'} = Carbon::now();
$record->save();
}
});
}
/**
* Get the route key for the model.
*
* #return string
*/
public function getRouteKeyName()
{
return 'uuid';
}
public function scopeAlive($query)
{
$query->where("status", config("constants.status.alive"));
}
}
My TestTrait looks like this :
use App\Entities\User;
use Carbon\Carbon;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
trait MedyqTrait
{
public static function getTableName()
{
return with(new static)->getTable();
}
public function scopeActive($query)
{
$query->where("status", config("constants.status.active"));
}
public function scopeInActive($query)
{
$query->where("status", config("constants.status.inactive"));
}
/**
* Mass (bulk) insert for Postgres Laravel 5
*
* insert([
* ['id'=>1,'value'=>10],
* ['id'=>2,'value'=>60]
* ]);
*
*
* #param array $rows
* #param null $table
* #param bool $skipUUid
* #param bool $timestamps
* #param bool $authorstamp
* #return bool
* #throws Exception
*/
public function bulkInsert(array $rows, $table = null, $skipUUid = false, $timestamps = true, $authorstamp = true)
{
$return_values = array_filter($rows, 'is_array');
if (!count($return_values) > 0) {
throw new Exception("This function expects a multidimensional associative array");
}
if (is_null($table)) {
$table = DB::getTablePrefix() . $this->getTable();
}
$rows = array_map(function ($item) use ($skipUUid, $timestamps, $authorstamp) {
$authenticated = auth()->check();
$authorId = auth()->id();
$time = Carbon::now();
if (!$skipUUid) {
$item['uuid'] = Str::orderedUuid();
}
if ($timestamps && !key_exists('created_by', $item) && $authenticated && $authorstamp) {
$item['created_by'] = $authorId;
}
if ($timestamps && !key_exists('updated_by', $item) && $authenticated && $authorstamp) {
$item['updated_by'] = $authorId;
}
if ($timestamps && !key_exists('created_at', $item)) {
$item['created_at'] = $time;
}
if ($timestamps && !key_exists('updated_at', $item)) {
$item['updated_at'] = $time;
}
return $item;
}, $rows);
$first = reset($rows);
$columns = implode(',',
array_map(function ($value) {
return "$value";
}, array_keys($first))
);
$values = implode(',', array_map(function ($row) {
return '(' . implode(',',
array_map(function ($value) {
return "'" . str_replace("'", "''", $value) . "'";
}, $row)
) . ')';
}, $rows)
);
$sql = "INSERT INTO {$table}({$columns}) VALUES {$values}";
return DB::statement($sql);
}
public function deletedBy()
{
return $this->belongsTo(User::class, "deleted_by", "id");
}
}
Guess you have problem with the syntax.
$invoice = Invoice::where('id', $invoice->id)
->with('items')
->withSum('items', 'total_amount')
->withSum('items', 'amount_paid')
->first();
withSum is probably available only since Laravel version 8.x, before that I think only withCount was available. But if you still want to use withSum in earlier version you can define a macro'
You could also try use LaravelSubQueryTrait trait directly in the model/models.
use Alexmg86\LaravelSubQuery\Traits\LaravelSubQueryTrait;
use Illuminate\Database\Eloquent\Model;
class Invoice extends Model
{
use LaravelSubQueryTrait;
Reference https://github.com/Alexmg86/laravel-sub-query
I am a newbie in Laravel. So I am trying to update my form but it kept returning fail because I used the findOrFail method on the Controller.
But when I tried to dump the Id, the Id does exists.
Only when I call it using the method, it returns null.
Route for update
Route::post('/alumni/updateProfile','AlumniController#update');
Update method
public function update(Request $request, User $user, Profile $profile)
{
$user->roles()->sync($request->roles);
$profile = Profile::findOrFail(Auth::user()->id);
$profile->name = $request->name;
$profile->matric_no = $request->matric_no;
$profile->contact_no = $request->contact_no;
$profile->address = $request->address;
$profile->batch_year = $request->batch_year;
$profile->graduation_year = $request->graduation_year;
$profile->date_of_birth = $request->date_of_birth;
$profile->area_of_interest = $request->area_of_interest;
$profile->start_date = $request->start_date;
$profile->company_name = $request->company_name;
$profile->job_title = $request->job_title;
$profile->social_network = $request->social_network;
$profile->save();
return view('/home', compact('profile'));
}
Profile model
class Profile extends Model
{
// protected $guarded = [];
protected $fillable = ['alumni_id'];
protected $table = 'profiles';
public $timestamps = false;
public function users()
{
return $this->belongsTo('App\User');
}
}
User model
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function roles()
{
return $this->belongsToMany('App\Role');
}
public function profiles()
{
return $this->belongsTo('App\Profile');
}
public function hasAnyRoles($roles)
{
if($this->roles()->whereIn('name', $roles)->first()){
return true;
}
return false;
}
public function hasRole($role)
{
if($this->roles()->where('name', $role)->first()) {
return true;
}
return false;
}
Glad if any of you noticed anything, thank you.
You can write findOrFail() in try catch blog and get the exception in catch blog to understand the error.
OR
you can write below code instead of findOrFail().
$profile = Profile::where('id', '=', Auth::user()->id);
if( $profile->count() ){
# Assignment of values to database columns fields and then save.
$profile->save();
} else {
# Print No Record Found.
}
there.
So, I'm making a section for My reports, and I need to get the reports, from the database, based on id of logged user. How can I make that in my controller? I'm using \App\Reports::get(), but I need to get it based on the id of logging user, which is saved in database at user_id.
public function myReports($page = null)
{
if ($user = Sentinel::check())
{
// return $user;
$data = $this->data;
$id = $user->id;
$data['title'] = "My Reports";
$reports = \App\Reports::get();
$data['leftside_profile'] = 'my-reports';
$find_contact[] = $id;
// DB::enableQueryLog();
$page = Input::get('page');
$perPage = 10;
$offset = ($page * $perPage) - $perPage;
{
$query->whereIn('user_id',$find_contact)
->where('type', '=', 'profile_updates');
});
return view('profile.my_reports',$data)
->with(compact('reports'));
}
else{
return redirect('home');
}
}
Reports model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Reports extends Model
{
protected $table = 'reports';
// public $timestamps = false;
protected $fillable = [
'user_id', 'username', 'user_id_posted', 'username_posted', 'news_id','opinion_id','event_id','career_solution_id', 'subject', 'why_reporting','why_reporting_message','additional_message','private'
];
public function career_solutionReport()
{
return $this->belongsTo('App\CareerSolution','career_solution_id','id');
}
public function eventReport()
{
return $this->belongsTo('App\Event','event_id','id');
}
public function newsReport()
{
return $this->belongsTo('App\News','news_id','id');
}
public function opinionReport()
{
return $this->belongsTo('App\Opinion','opinion_id','id');
}
public function user()
{
return $this->belongsTo('App\User','user_id','id');
}
}
If the user is logged in you can call Sentinel::getUser()->id to retrieve the user id.
Change
$reports = \App\Reports::get();
To
$reports = \App\Reports::where('user_id', Sentinel::getUser()->id)->get();