Laravel Job class has incomplete passed model - laravel

I am trying to pass a model to job class and when the model is sent to job class, it's incomplete there. What I mean is that it shows only two attributes there instead of 10. $queue_match is complete model (all attributes included, everything is fine) but when it is sent to Job class, then I only see two attributes.
PS: I have included my model at the top of Job class,
$z = dispatch(new updateMatchStatus($queue_match))->onConnection('database')->delay(now()->addMinutes('1'));
namespace App\Jobs;
use App\Http\Controllers\AdminController;
use App\Models\Match;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class updateMatchStatus implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $queue_match;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct(Match $queue_match)
{
//
$this->queue_match = $queue_match;
// dd($queue_match);
}
/**
* Execute the job.
*
* #return void
*/
public function handle(Match $queue_match)
{
$now = Carbon::now('PKT');
$now = Carbon::parse($now, 'PKT')->startOfMinute();
// registration close hack, will set Match status to F 30 mins before due time.
$now = $now->addMinutes(30);
$due_time = Carbon::parse($queue_match->due_time, 'PKT');
if ($now->greaterThan($due_time)) {
$queue_match->status = 'F';
// dd($queue_match);
$queue_match->save();
}
}
}
just two attributes in Screenshot
As requested, Here is Match Class
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Match extends Model
{
//
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'platform', 'category', 'map', 'fee', 'is_elite', 'due_time', 'status'
];
public function getPlatformAttribute($value) {
if ($value == 'M') {
return $value ."obile";
}
else {
return $value ."mulator";
}
}
// default attributes
protected $attributes= [
'status' => 'A',
'is_elite' => false
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
// hidden fields for return response
protected $hidden = [
'created_at', 'updated_at',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
];
public function registrations() {
return $this->hasMany('App\Models\Registration', 'match_id', 'id');
}
public function results() {
return $this->hasMany('App\Models\Result', 'match_id', 'id');
}
}
AND, this is how I get the $queue_match which is passed to job.
$queue_match = Match::create([
'category' => $request['category'],
'platform' => $request['platform'],
'map' => $request['map'],
'fee' => $request['fee'],
'due_time' => $request['due_time'],
]);

Related

How to send only one event in Pusher channel and then for database notification store for all users

I've created a broadcast channel App.Models.Admin.Notify where all the admin users will be subscribed to this channel by default.
<?php
use Illuminate\Support\Facades\Broadcast;
Broadcast::channel('App.Models.Admin.Notify', function ($m) {
return !is_null($m) && $m->getMorphClass() === 'admin';
});
And this is the Notifications/Base.php where i've set ['database', 'broadcast', OneSignal::class] as notification channels
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Notifications\Messages\BroadcastMessage;
use NotificationChannels\OneSignal\OneSignalMessage;
use App\Channels\OneSignal;
abstract class Base extends Notification implements ShouldBroadcast, ShouldQueue
{
use Queueable;
public $model;
protected string $icon;
public function __construct(mixed $m = null)
{
$this->model = $m;
}
/**
* Get notify id
*
* #return string
*/
protected function getNotifyId(): string
{
return $this->id;
}
/**
* Get icon path
*
* #return string
*/
protected function getIcon(): string
{
return asset('favicon.ico');
}
/**
* Get notification link
*
* #return string
*/
protected function getLink(): string
{
return asset('favicon.ico');
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return \App\Channels\PusherBeams\PusherMessage
*/
public function via($notifiable)
{
return [
'database',
'broadcast',
OneSignal::class
];
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return array_merge(
[
'link' => $this->getLink(),
'icon' => $this->getIcon(),
],
$this->getData($notifiable)
);
}
/**
* Get data of message.
*
* #param mixed $notifiable
* #return array
*/
protected function getData($notifiable)
{
return [
'title' => 'hello',
'body' => 'world'
];
}
/**
* Create onesignal message of Web
* #param mixed $notifiable
* #return \NotificationChannels\OneSignal\OneSignalMessage
*/
public function toWeb($notifiable)
{
$data = $this->toArray($notifiable);
return OneSignalMessage::create()
->setSubject($data['title'])
->setBody($data['body'])
->setUrl($data['link']);
}
/**
* Create onesignal message of Android
* #param mixed $notifiable
* #return \NotificationChannels\OneSignal\OneSignalMessage
*/
public function toAndroid($notifiable)
{
$data = $this->toArray($notifiable);
return OneSignalMessage::create()
->setSubject($data['title'])
->setBody($data['body'])
->setData('url', str_replace('https://', 'gamepts://', $data['link']));
}
/**
* Websocket message
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\BroadcastMessage
*/
public function toBroadcast($notifiable)
{
return (new BroadcastMessage($this->toArray($notifiable)))->onQueue('pusher');
}
}
So this is the basic setup for my Notifications and broadcasting.
I've a job which runs every minutes and if any reports are found then it should send the notification if any reports are found.
<?php
namespace App\Console\Commands;
use Carbon\Carbon;
use App\Models\MerchantDeposit;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Notification;
class CheckCashIn extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'check:cashin';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Check expiration of cash in orders';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
$setting = app(\App\Settings\CurrencySetting::class)->currency;
$expired_limit = app(\App\Settings\AdminSetting::class)->expired_payin_limit_notify;
$reports = [];
foreach ($setting as $currency => $s) {
$expired_minutes = $s['expired_minutes'];
$k = MerchantDeposit::where('status', MerchantDeposit::STATUS['PENDING'])
->where('currency', $currency)
->where('created_at', '<=', Carbon::now()->subMinutes($expired_minutes))
->update(['status' => MerchantDeposit::STATUS['EXPIRED']]);
$o = MerchantDeposit::where('merchant_deposits.status', MerchantDeposit::STATUS['EXPIRED'])
->join('reseller_bank_cards', 'reseller_bank_cards.id', 'merchant_deposits.reseller_bank_card_id')
->join('resellers', 'resellers.id', 'reseller_bank_cards.reseller_id')
->where('merchant_deposits.currency', $currency)
->where('merchant_deposits.created_at', '<=', Carbon::now()->subMinutes($expired_minutes))
->having(DB::raw('COUNT(resellers.name)'), '>=', $expired_limit)
->select('resellers.name', DB::raw('COUNT(resellers.name) AS total_expired'), DB::raw('TRUNCATE(SUM(merchant_deposits.amount), 2) AS total_amount'), 'merchant_deposits.currency')
->groupBy('resellers.name', 'merchant_deposits.currency')
->get();
if (!empty($o->toArray()) && $k > 0) {
$reports[$currency] = [];
foreach ($o as $k => $v) {
$reports[$currency][$v->name] = $v->total_expired;
$reports[$currency]['Total Amount'] = $v->total_amount;
}
}
}
if (!empty($reports)) {
Notification::send(\App\Models\Admin::all(), new \App\Notifications\DepositExpiredReport($reports));
}
}
}
And in Model/Admin.php i've set receivesBroadcastNotificationsOn to update the channel name for the broadcast to send into pusher.
<?php
namespace App\Models;
use App\Trait\HasJWTSubject;
use App\Trait\UserLogsActivity;
use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Hash;
use Illuminate\Notifications\Notifiable;
use Laravel\Lumen\Auth\Authorizable;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Spatie\Permission\Traits\HasRoles;
/**
* Model of admin
* #package Models
*/
class Admin extends Model implements AuthenticatableContract, AuthorizableContract, JWTSubject
{
use Authenticatable, Authorizable, HasFactory, HasJWTSubject;
use UserLogsActivity;
use Notifiable;
use HasRoles;
protected $fillable = [
'name',
'username',
'password',
'status',
'timezone'
];
protected $hidden = [
'password',
];
protected $casts = [
'status' => 'boolean',
];
public const STATUS = [
'DISABLED' => false,
'ACTIVE' => true,
];
public function getIsSuperAdminAttribute()
{
return $this->hasRole('Super Admin');
}
public function setPasswordAttribute($value)
{
$this->attributes['password'] = Hash::needsRehash($value) ? Hash::make($value) : $value;
}
public function devices()
{
return $this->morphMany(Device::class, 'user');
}
public function receivesBroadcastNotificationsOn()
{
return 'App.Models.Admin.Notify';
}
}
When the notification is triggered from Notification::send(\App\Models\Admin::all(), new \App\Notifications\DepositExpiredReport($reports)); it will send broadcast notification multiple times to same broadcast channel as shown in the screenshot below
From Notification::send(\App\Models\Admin::all(), new \App\Notifications\DepositExpiredReport($reports)); it is fine to save the notification records for all the admin in database notification but for pusher i want the notification event to sent only once instead of sending multiple times ie 'x' number of admins.
Lets say i have 100 admin users then now pusher will send the event to same channel 100 times. So i want to minimize the pusher event to just 1 channel where all the admin users subscribed can receive the notification but it should also save the records for 100 users in the notification table of database.

Laravel Relationship Null

I am having an issue following a tutorial on YouTube about relationships.
I have replicated this code from the tutorial and I keep getting errors.
I've tried changing the controller code from auth() to app etc.
Also, I've tried re-running migrations:fresh etc and nothing.
User Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Cashier\Billable;
class User extends Authenticatable
{
use Notifiable, Billable;
/**
* 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',
];
/**
* Get the Instance associated with the user.
*
* #return HasMany
*/
public function instance()
{
return $this->hasMany(Instance::class);
}
}
Instance Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Instance extends Model
{
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'name'
];
public function user()
{
return $this->belongsTo(User::class);
}
}
Controller
<?php
namespace App\Http\Controllers;
class SyncController extends Controller
{
public function successful()
{
return auth()->user()->instance()->create(['name' => 'test']);
}
}
Error
Call to a member function instance() on null {"exception":"[object] (Error(code: 0): Call to a member function instance() on null at /home/#/cc.#.io/app/Http/Controllers/SyncController.php:14)
[stacktrace]
Edit:
Route::middleware(['auth'])->group(function() {
Route::get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
Route::get('/subscribe', SyncController::class);
});
Check if your route is guarded by auth middleware. If not you can add that in order to fix. You might use Route group like following -
Route::group(['middleware' => ['auth']], function () {
Route::resource('your_url', 'YourController');
// Or whatever route you want to add...
});
This is because the auth()->user is getting null and it will be necessary to check if the value was actually received after the call was made.

Single page application notification problem

I have a single page application. I use a vuejs as a front-end and laravel 5.7 as a backend. I'm using a webPush and service worker to push notifications to users. The problem is when the user is offline and return back online a lot of notifications are pushed. I need to push only the last notifications in service worker queue and the number of other notifications in the queue.
//Listen to Push from service worker file
self.addEventListener('push', (e) => {
let data
if (e.data) {
data = e.data.json()
}
const options = {
body: data.body,
icon: '/images/fav/android-icon-192x192.png',
image: '/storage/users'+data.image||'/images/profiles/profile.png',
badge: '/images/fav/android-icon-96x96.png',
actions:data.actions,
data:data.data
}
e.waitUntil(self.registration.showNotification(data.title, options))
});
self.addEventListener('notificationclick', function(event) {
var url = event.notification.data.location;
event.waitUntil(
clients.matchAll({type: 'window'}).then( windowClients => {
for (var i = 0; i < windowClients.length; i++) {
var client = windowClients[i];
if (client.url === url && 'focus' in client) {
return client.focus();
}
}
if (clients.openWindow) {
return clients.openWindow(url);
}
})
);
});
//User model
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;
use NotificationChannels\WebPush\HasPushSubscriptions;
class User extends Authenticatable implements JWTSubject
{
use Notifiable;
use HasPushSubscriptions;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'fname','lname',"username", 'email', 'password',"code","active"
];
protected $guard_name = 'api';
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
// Rest omitted for brevity
/**
* Get the identifier that will be stored in the subject claim of the JWT.
*
* #return mixed
*/
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* #return array
*/
public function getJWTCustomClaims()
{
return [];
}
}
//example for notification class
<?php
namespace App\Notifications;
use App\PostEvent;
use App\User;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use NotificationChannels\WebPush\WebPushChannel;
use NotificationChannels\WebPush\WebPushMessage;
class interestEvent extends Notification implements ShouldQueue
{
use Queueable;
/**
* Create a new notification instance.
*
* #return void
*/
public $event;
public $user;
public function __construct(PostEvent $event,User $user)
{
$this->event=$event;
$this->user=$user;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['database','broadcast',WebPushChannel::class];
}
public function toDatabase($notifiable)
{
$message="event you are interested in will begin tomorrow";
$name=$this->user->fname;
if($name){
$name .=" ".$this->user->lname;
}
else
{
$name=$this->user->username;
}
return [
'user_id' => $this->user->id,
"name"=>$name,
'message' => $message,
'image'=>$this->user->image,
'post_id'=>$this->event->post_id,
'eventName'=>$this->event->name,
];
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
$message="event you are interested in will begin tomorrow";
$name=$this->user->fname;
if($name){
$name .=" ".$this->user->lname;
}
else
{
$name=$this->user->username;
}
return [
'id' => $this->id,
'read_at' => null,
'data' => [
'user_id' => $this->user->id,
'message' => $message,
"name"=>$name,
'image'=>$this->user->image,
'post_id'=>$this->event->post_id,
'eventName'=>$this->event->name,
'location'=>"/home/posts/".$this->event->post_id
],
];
}
public function toWebPush($notifiable, $notification)
{
$message="event you are interested in will begin tomorrow";
$name=$this->user->fname;
if($name){
$name .=" ".$this->user->lname;
}
else
{
$name=$this->user->username;
}
$message="(".$this->event->name.") ".$message;
return (new WebPushMessage)
->title('Ajwbtcom')
->body($message)
->action('See Event', "/home/posts/".$this->event->post_id)
->image($this->user->image)
->data( [
'user_id' => $this->user->id,
'message' => $message,
"name"=>$name,
'image'=>$this->user->image,
'post_id'=>$this->event->post_id,
'eventName'=>$this->event->name,
'location'=>"/home/posts/".$this->event->post_id
]);
}
}
You can use the tag option when you call showNotification in order to display only the last notification:
https://notifications.spec.whatwg.org/#using-the-tag-member-for-a-single-instance

Laravel queues issues when I pass data from controller to jobs

I'm having issue fixing the queue part for Laravel.
I have a contact form which works perfectly. I submit the form and a mail is being sent to me with the input details from the form.
But the issue is that if you do not use the Laravel Queues then the UX is lacking because of the waiting time before the mail is being sent and after getting the success message.
So now I want to implement the queuing part, but im not doing it right. Im still a noob at it...
Here is my controller
KontaktformController.php
<?php
namespace App\Http\Controllers;
use App\Jobs\SendEmailJob;
use Carbon\Carbon;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Session;
use App\Kontaktform;
use Illuminate\Http\Request;
use App\Mail\SendEmailMailable;
class KontaktformController extends Controller
{
public function create()
{
return view('kontakt');
}
public function store(Request $request) {
$this->validate($request, [
'name' => 'required|string',
'mobile' => 'required',
'email' => 'required|email',
'subject' => 'required',
'message' => 'required',
]);
/*
Add mail functionality here.*/
$kontakt = new Kontaktform([
'navn' => $request['name'],
'mobilnr' => $request['mobile'],
'fastnetnr' => $request['landline'],
'mail' => $request['email'],
'emne' => $request['subject'],
'beskrivelse' => $request['message']
]);
$kontakt->save();
//$user['email'] = 'test#test.com';
$job = (new SendEmailJob($request['email']))
->delay(Carbon::now()->addSeconds(3));
dispatch($job);
}
}
SendEmailJob.php
<?php
namespace App\Jobs;
use App\Mail\SendEmailMailable;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Mail;
class SendEmailJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $user;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct($user)
{
$this->user = $user;
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
$email = new SendEmailMailable('test#test.dk');
Mail::to('admin#admin.dk')->send($email);
}
}
SendEmailMailable.php
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class SendEmailMailable extends Mailable
{
use Queueable, SerializesModels;
public $request;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($request)
{
$this->request = $request;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->from('test#test.dk')->view('mail.kontaktform');
}
}
kontaktform.blad.php
{{$request['email']}}
In your kontaktform.blad.php (which should be named kontaktform.blade.php btw), you expect the data to be an array because you try to fetch the index ['email'] though in your SendEmailJob.php in the method handle() you pass your email as a string.
So what you should change it to the following:
$email = new SendEmailMailable(['email' => 'test#test.dk']);
or do the following in the controller & in the job:
Controller:
$job = (new SendEmailJob($request))
->delay(Carbon::now()->addSeconds(3));
Job:
protected $request;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct($request)
{
$this->request = $request;
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
$mailable = new SendEmailMailable($this->request);
Mail::to('admin#admin.dk')->send($mailable);
}
Now all data from the request is should be available in your blade template.
I found the issue. I didnt pass data from mailable to my blade
public function build()
{
return $this->view( 'mail.kontaktform' )->with( [
'request' => $this->request,
] );
}

Eager Loading with Eloquent

I have the following code:
$users = User::with('profile')->paginate($count);
and:
$roles = Role::withCount('users')->get();
Now using laravel-debugbar and when I open my users page what I see is that 107 queries are being executed making the page load really slowly and I have a feeling that when I add more users the number total number of queries executed is going to increase. I have looked at the code and right now I can't tell what is wrong with it or how to reduce the number of queries being generated.
These are my models:
User.php
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Kodeine\Acl\Traits\HasRole;
class User extends Authenticatable
{
use HasRole, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
protected $table = "users";
protected $appends = ['role'];
public function profile()
{
return $this->hasOne('App\Models\Profile');
}
public function getRoleAttribute() {
return $this->getRoles();
}
}
Role.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Kodeine\Acl\Traits\HasPermission;
use Cviebrock\EloquentSluggable\Sluggable;
class Role extends Model
{
use HasPermission, Sluggable;
protected $table = "roles";
/**
* The attributes that are fillable via mass assignment.
*
* #var array
*/
protected $fillable = ['name', 'slug', 'description'];
/**
* Roles can belong to many users.
*
* #return Model
*/
public function users()
{
return $this->belongsToMany('App\Models\User', 'role_user', 'role_id', 'user_id');
}
/**
* List all permissions
*
* #return mixed
*/
public function getPermissions()
{
return $this->getPermissionsInherited();
}
/**
* Checks if the role has the given permission.
*
* #param string $permission
* #param string $operator
* #param array $mergePermissions
* #return bool
*/
public function can($permission, $operator = null, $mergePermissions = [])
{
$operator = is_null($operator) ? $this->parseOperator($permission) : $operator;
$permission = $this->hasDelimiterToArray($permission);
$permissions = $this->getPermissions() + $mergePermissions;
// make permissions to dot notation.
// create.user, delete.admin etc.
$permissions = $this->toDotPermissions($permissions);
// validate permissions array
if ( is_array($permission) ) {
if ( ! in_array($operator, ['and', 'or']) ) {
$e = 'Invalid operator, available operators are "and", "or".';
throw new \InvalidArgumentException($e);
}
$call = 'canWith' . ucwords($operator);
return $this->$call($permission, $permissions);
}
// validate single permission
return isset($permissions[$permission]) && $permissions[$permission] == true;
}
/**
* #param $permission
* #param $permissions
* #return bool
*/
protected function canWithAnd($permission, $permissions)
{
foreach ($permission as $check) {
if ( ! in_array($check, $permissions) || ! isset($permissions[$check]) || $permissions[$check] != true ) {
return false;
}
}
return true;
}
/**
* #param $permission
* #param $permissions
* #return bool
*/
protected function canWithOr($permission, $permissions)
{
foreach ($permission as $check) {
if ( in_array($check, $permissions) && isset($permissions[$check]) && $permissions[$check] == true ) {
return true;
}
}
return false;
}
/**
* Return the sluggable configuration array for this model.
*
* #return array
*/
public function sluggable()
{
return [
'slug' => [
'source' => 'name'
]
];
}
}
Profile.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
protected $table = "profiles";
public function user()
{
return $this->belongsTo('App\Models\User');
}
}
This seems to be the query being repeated:
select `roles`.*, `role_user`.`user_id` as `pivot_user_id`, `role_user`.`role_id` as `pivot_role_id`, `role_user`.`created_at` as `pivot_created_at`, `role_user`.`updated_at` as `pivot_updated_at` from `roles` inner join `role_user` on `roles`.`id` = `role_user`.`role_id` where `role_user`.`user_id` = '4'
Edit:
The issue seems to be coming from my roles, I'm looking at the code in my controller and in my model and I can't tell what is wrong. I changed $roles = Role::withCount('users')->get(); to $roles = Role::with('users')->withCount('users')->get(); and now I have fewer queries generated (71 still a lot).
It's the appends role attribute on the user model that is causing so many excessive queries. As a test comment out appends roles and test how many queries run then. You'll likely need to lazy load roles to keep the number of queries minimized.

Resources