Round robin not functioning well - laravel

I try to create a function using round robin where all user in a group will be moderator for every meeting created.For example, a group have 2 users, I managed to create the first two meeting with the two users, but when I created the third meeting, it become null.
public function addsession(Request $req)
{
$mod = null;
$latestUserId=Meeting::where('groupID', $req->groupID)
->latest('id')
->first()
?->meetingModerator;
//the first meeting or all the users have already had their turn
$firstUserId=DB::table('group_user')
->where('group_id', $req->groupID)
->orderBy('user_id')
->first()
?->user_id;
//second time meeting is being held
if ($latestUserId) {
$nextUserId=DB::table('group_user')
->where('group_id', $req->groupID)
->where('user_id', ">", $latestUserId)
->orderBy('user_id')
->first()
?->user_id;
$mod = $nextUserId;
} else {
$mod = $firstUserId;
}
$data = new Meeting;
$data->groupID = $req->groupID;
$data->meetingDate = $req->meetingDate;
$data->meetingTime = $req->meetingTime;
$data->meetingModerator = $mod;
$data->save();
}
Model group.php
class Group extends Model
{
use SoftDeletes;
use HasFactory;
public $timestamps=true;
protected $dates = ['deleted_at'];
public function creators()
{
return $this->belongsToMany(User::class);
}
}
Model user.php
class User extends Authenticatable
{
use SoftDeletes;
use HasApiTokens;
use HasFactory;
use HasProfilePhoto;
use Notifiable;
use TwoFactorAuthenticatable;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'name',
'email',
'password',
'role'
];
protected $dates = ['deleted_at'];
public function grp()
{
return $this->belongsToMany(Group::class);
}
/**
* The attributes that should be hidden for serialization.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
'two_factor_recovery_codes',
'two_factor_secret',
];
/**
* The attributes that should be cast.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* The accessors to append to the model's array form.
*
* #var array
*/
protected $appends = [
'profile_photo_url',
];
}
Model meeting.php
class Meeting extends Model
{
use HasFactory;
public function gr()
{
return $this->belongsTo('App\Models\Group','groupID');
}
}

Related

Attempt to read property "name" on null (View: C:\xampp\htdocs\Moja_OTT\resources\views\premium\profile.blade.php)

I want a simple program that shows the user profile after login. I used session and middleware. But it is saying that the name property is null. Please help me solve this error. I have used User model. The value of the properties are not retrieving from the database.
Blade code:
<h1>Profile</h1>
<h2>Welcome Mr/Ms {{$user->name}}</h2>
Logout
Model:
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use App\Models\PremiumModel;
class User extends Authenticatable implements MustVerifyEmail
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $table = 'users';
protected $primaryKey = 'user_id';
protected $timestamp = false;
protected $fillable = [
'name',
'email',
'password',
'type',
'email_verified_at',
'pro_pic',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
function admin()
{
return $this->hasOne('App\Models\admin', 'user_id', 'admin_id');
}
function premium()
{
return $this->hasMany(PremiumModel::class, 'user_id', 'user_id');
}
}
Controller code:
function profile()
{
$user = User::where('user_id',session()->get('logged'))->first();
return view('premium.profile')->with('user',$user);
}
Here, logged is the middleware.
You can try hasOne in the User model:
public function premium()
{
return $this->hasOne(PremiumModel::class, 'user_id', 'user_id');
}
Because hasMany returned an array, but hasOne returned just a single Object

compatible with Illuminate\Foundation\Auth\User::sendEmailVerificationNotification()

I need to change default resetpassword message so i make my own ResetPassword notification and when i do that I got this Error Declaration of App\User::sendEmailVerificationNotification($token) should be compatible with Illuminate\Foundation\Auth\User::sendEmailVerificationNotification()
code in User model:
<?php
namespace App;
use App\admin\Course;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable; // حتى اقدر ارسل اله اشعار
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password','type','mobile',
];
/**
* 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',
];
public function courses()
{
return $this->belongsToMany(Course::class, 'course_user', 'user_id', 'course_id');
}
public function routeNotificationForNexmo($notification)
{
return $this->mobile;
}
public function sendPasswordResetNotification($token)
{
$this->notify(new \App\Notifications\ResetPassword($token));
}
public function sendEmailVerificationNotification($token)
{
$this->notify(new \App\Notifications\VerifyEmail($token));
}
}
Why !!

Lazy eager loaded relationship missing in toArray()

Laravel 5.8
I am lazy loading an user with the related customer which has a one-to-one-relation with a crmaccount-object
The models are working so that when i retrieve the eager-loaded entity it shows all of the nested relationships.
One row later i use the "toArray()" method on that object and the output is missing the third-level-relations.
The only thing which maybe some kind of special regarding the "crmaccount"-model is that it holds a column which is json an has to be casted.
Any idea what is going on here?
All of these happens in a middleware. No difference if i use with or load.
public function handle($request, Closure $next)
{
$UserData = \Auth::user();
if($UserData){
$User = \App\Login::with(['role','customer','customer.crmaccount'])->find($UserData->id);
dump($User);
dd($User->toArray());
$UserData['isAdmin'] = false;
if($UserData['role']['name'] === 'Admin'){
$UserData['isAdmin'] = true;
}
$request->request->add(['UserData' => $UserData]);
}
return $next($request);
}
Login
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Login extends Authenticatable{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password','customer_id','role_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',
];
/* */
public function Role(){
return $this->belongsTo('App\Role');
}
public function Customer(){
return $this->belongsTo('App\Customer');
}
/**
* [hasOpportunities Ruft alle Opportunities des Users ab. Da diese lediglich zwei Entitäten weiter sind, kann anstatt von dot-notated Lazy-Load auch die hasManyThrough-ORM-Methode genutzt werden]
* #return [hasManyThrough-Relation] [Die hasManyThrough-ORM-Beziehung]
*/
public function hasOpportunities(){
return $this->hasManyThrough(
'App\Opportunity',
'App\Customer',
'id',
'customer_id',
'customer_id'
);
}
/**
* [hasSalesreps Ruft alle SalesReps des Users ab. Da diese lediglich zwei Entitäten weiter sind, kann anstatt von dot-notated Lazy-Load auch die hasManyThrough-ORM-Methode genutzt werden]
* #return [hasManyThrough-Relation] [Die hasManyThrough-ORM-Beziehung]
*/
public function hasSalesreps(){
return $this->hasManyThrough(
'App\Salesrep',
'App\Customer',
'id',
'customer_id',
'customer_id'
);
}
}
Customer
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model{
public $timestamps = false;
protected $visible = ['id','name'];
protected $fillable = ['name'];
public function crmaccount(){
return $this->hasOne('App\Crmaccount');
}
public function Salesreps()
{
return $this->hasMany('App\Salesrep');
}
public function Prospects()
{
return $this->hasMany('App\Prospect');
}
public function Trees()
{
return $this->hasMany('App\Salesreptrees');
}
public function Opportunities()
{
return $this->hasMany('App\Opportunity');
}
public function User()
{
return $this->hasMany('App\Login');
}
}
Crmaccount
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Crmaccount extends Model{
public $timestamps = false;
protected $visible = ['id','name','crm_system','customer_id','crm_api_config'];
protected $fillable = [
'name','crm_system','customer_id','crm_api_config'
];
protected $casts = [
'crm_api_config' => 'array'
];
public function customer(){
return $this->belongsTo('App\Customer');
}
}
On every model, there is a protected $visible = []; and protected $hidden = [] attribute. These control the attributes that are available when the model is converted to an object, array or json. This includes relationships, as Laravel internally converts them to attributes, so omitting them from visible, or including them in hidden will cause them to not be available.
In Customer.php:
protected $visible = ['id','name'];
Since crmaccount is not in that array, only id and name will be available. Simply add crmaccount to the array to handle:
protected $visible = ['id','name', 'crmaccount'];
Alternatively, use hidden to explicitly set the attributes you don't want to show, and relationship, if loaded via ->with() will show by default.

laravel policy gves flalse

I am new to laravel and now trying to learn policies so I created the following models:
class group extends Model
{
protected $fillable = [
'id','book_id',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
];
public function users(){
return $this->belongsToMany('BOOK_DONATION\User')->withPivot('last_seen_id');
}
}
and :
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email','country','state/provience','city', 'token', 'password','postal_code',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password','verfied', 'remember_token',
];
public function Book(){
return $this->hasMany('App\Book');
}
public function groups(){
return $this->belongsToMAny('BOOK_DONATION\group')->withPivot('last_seen_id');
}
}
and :
class group_user extends Model
{
//
protected $table='group_user';
protected $fillable = [
'user_id','group_id','last_seen_id'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
];
}
now the group_user is model for the intermidate table required for the many to many relation between users and groups
and here is my policy:
class group_userPolicy
{
use HandlesAuthorization;
/**
* Determine whether the user can view the group_user.
*
* #param \BOOK_DONATION\User $user
* #param \BOOK_DONATION\group_user $groupUser
* #return mixed
*/
public function view(User $user, group_user $groupUser)
{
//
return in_array($user->id,$groupUser->user_id);
}
}
and here is the specific programming lines from controller related :
$grouUser=group_user::where('group_id',$group_id)->pluck('user_id');
if(Auth::user()->cant('joinChat',$grouUser)) return redirect('/sorry');
now I always get redirected to sorry page but I have the right yo join chat so what is wrong?

eloquent one-To-Many-To-Many

Hi everyone I start with Laravel and eloquent and already I have a problem.
I have users, each user can have multiple vehicles and a vehicle can have multiple rentals. I want to list all rentals of each vehicle belonging to the current user.
User model:
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function vehicule()
{
return $this->hasMany('App\Models\Vehicule');
}
Vehicule model:
use Illuminate\Database\Eloquent\Model;
class Vehicule extends Model
{
protected $fillable = [
'user_id',
'published',
'rented'
];
public function user()
{
return $this->belongsTo('App\User');
}
public function rental()
{
return $this->hasMany('App\Models\Rental');
}
Rental model:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Rental extends Model
{
protected $fillable = [
'from_date',
'to_date',
'amount_total',
'vehicule_id'
];
public function vehicule()
{
return $this->belongsTo('App\Models\Vehicule');
}
}
You can use your existing relationships:
$rentals = $user->load('vehicule.rental')->pluck('vehicule.rental')->collapse();
Or add a HasManyThrough relationship to User:
public function rental()
{
return $this->hasManyThrough(Rental::class, Vehicule::class);
}
$rentals = $user->rental;

Resources