Laravel - can a method on Eloquent model class ignore Trait? - php

I have a User Model class that uses UserHasTeams trait, and this User class has a relationship method called projects. Now my question is, is it possible that somehow this projects method ignores the trait UserHasTeams because it appends the team_id in the where clause of my eloquent query, which I don't want. Here is the code
<?php
namespace App;
class User extends Authenticatable
{
use Notifiable, Billable, UserHasTeams;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'company_id', 'role', 'status', 'trial_ends_at',
'address_line_1', 'address_line_2', 'city', 'state', 'zipcode', 'country_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',
];
protected $dates = ['trial_ends_at'];
public function company() {
return $this->belongsTo(Company::class);
}
public function projects() {
return $this->hasMany(Project::class);
}
}
whenever I use Project::all(), it appends team_id which is accepted but for some instances, I don't want this projects method to use Trait, is It possible? If yes, how?
Thanks in advance.

Related

Userpermission pivot-function is only accessible via the Auth class

I have a simple Userpermission System consisting of 3 tables: users, permissions and the pivot table permission_user.
This is the User model:
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
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',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function permissions()
{
return $this->belongsToMany('App\Permission');
}
}
and here is the Permission Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Permission extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'description', 'level', 'parentpermission',
];
public function users()
{
return $this->belongsToMany('App\User');
}
}
Now when I try to get all the permissions of the currently logged in user with this:
$user_permissions = Auth::user()->permissions()->get();
it works without problems.
But when I try to get another Users Permissions like this:
$user_permissions = User::where('id', '=', $userid)->permissions()->get();
I get the following error:
Method Illuminate\Database\Eloquent\Collection::permissions does not exist.
How do I proceed?
I think you're missing first() here, since you can't get relations of a query builder object. Try this :
$user_permissions = User::where('id', '=', $userid)->first()->permissions()->get();
This first() will actually return User object, and then you can load its relations.
simply you can just add first() method to get just one record and get it's permissions, try this:
$user_permissions = User::where('id', '=', $userid)->first()->permissions;
There's no need to use get() method, this will get all the user permissions directely
Do this -
$user_permissions = User::find($userid)->permissions()->get();

How to have a different Email column name and in hasOne relation table for password reset Laravel 5.8

I tried to change default email field for reset password (the email field is in other table that my User model has hasOne relation to this table, and field name is Email not email), I override method getEmailForPasswordReset in User model with field Email from hasOne relation from another table. And now its just refresh the page and nothing happens, its even didn't write reset request with token to password_resets table.
If I go with the flow route->controller->method, I'm getting to Illuminate\Foundation\Auth\SendsPasswordResetEmails to method sendResetLinkEmail and here I think this check $this->validateEmail($request) doesn't work. If I doing dd to $request before this check I get my request.
Below I've added my image of overriding the getEmailForPasswordReset method
This is my User model:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
/**
* Class User
* #package App
*/
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'Allowed_Users', 'Email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
protected $table = 'sometable';
protected $primaryKey = 'recordId';
public $timestamps = false;
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
'Allowed_Users' => 'integer',
];
public function property()
{
return $this->hasOne('App\Property', 'id', 'Allowed_Users');
}
public function getEmailForPasswordReset()
{
$user_property = $this->property()->get();
return $user_property[0]->Email;
}
}
Thx for help

Laravel class not being found in a model

I am trying to get my project to use authorization roles to restrict users to certain featuers and I am following along with a tutorial. When I make a call to a class in my user.php file I am getting an error that the class App\Role can't be found. I am not sure if it is a namespace issue but I can't get to the bottom of it. I believe it is the roles function that is giving me this issue.
<?php
namespace EliteWorker;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'address', 'phone', 'email', 'password',
];
/**
* 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 roles() {
return $this->belongsToMany('App\Role');
}
public function hasAnyRoles($roles){
return null !== $this->roles()->whereIn('name', $roles)->first();
}
public function hasAnyRole($role){
return null !== $this->roles()->where('name', $role)->first();
}
}
You changed the namespace to EliteWorker so if the Model class RoleĀ is generated with Artisan, it'll also have that namespace
public function roles()
{
return $this->belongsToMany('EliteWorker\Role');
}
Note that you can also get the model base name by calling the class static property
public function roles()
{
return $this->belongsToMany(Role::class);
}
No need to import it if it's in the same namespace
Also note that the artisan command app:name has been removed in Laravel 6 to encourage developers to use the generic App namespace

How can I construct query with laravel query builder correctly?

I have two models: Users and Message. They are bound together with relation one to many (one user can send many messages). Table Users has a column "email" and table Message has column "r_email" (this is the same field). So I need to make query like "SELECT * FROM Users, Message WHERE Users.email = Message.r_email. How can I do this?
I tried something like this:
$messages = App\Message::with('users')->where('users.email', '=', 'messages.r_email')->get();
But it gives me Error. What is a problem?
Models are bound in this way:
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',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function messages()
{
return $this->hasMany(Message::class);
}
}
And the code for Message model:
class Message extends Model
{
protected $fillable = ['message', 'r_email'];
public function user()
{
return $this->belongsTo(User::class);
}
}
try
$messages = App\Message::with('users')->whereRaw('users.email = messages.r_email')->get();
Try this
$messages = DB::table('users')
->leftJoin('message', 'users.email', '=', 'message.r_email')
->get();
Hope this help.

Laravel Eloquent Eager Loading multiple relationships with pagination

I have a site running Laravel 4.2 that I am working on right now, the problem is that I have a single model for orders and another child model for items that belong to the order. The items also have a child model for size information and image information.
I have my query:
$orders = Auth::user()->orders()->with('items','items.size','items.image')->get()->toArray();
This returns what I am expecting, but I want to have the results paginated using Laravel's pagination. I had expected this to work:
$orders = Auth::user()->orders()->with('items','items.size','items.image')->paginate( 10 );
This returns a blank white page and a 500 error and for the life of me I can't figure out how to get this to work correctly.
Here are my various models: User.php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
protected $fillable = array( 'first_name', 'last_name', 'address', 'city', 'state', 'zip', 'lat', 'lng', 'email', 'phone', 'password', 'hash', 'type', 'blocked', 'created_at', 'updated_at', 'deleted_at' );
public function setPasswordAttribute( $value ) {
return $this -> attributes['password'] = Hash::make( $value );
}
public function projects() {
return $this -> belongsToMany('Project');
}
public function orders() {
return $this->hasMany('PrintOrder');
}
public function bookings() {
return $this -> belongsToMany('Booking');
}
}
PrintOrder.php
use Illuminate\Database\Eloquent\SoftDeletingTrait;
class PrintOrder extends Eloquent {
use SoftDeletingTrait;
protected $dates = ['deleted_at'];
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'print_orders';
protected $fillable = array( 'project_id', 'user_id', 'status', 'created_at', 'updated_at', 'deleted_at' );
public function items() {
return $this->hasMany('PrintOrderItem');
}
}
PrintOrderItem.php
use Illuminate\Database\Eloquent\SoftDeletingTrait;
class PrintOrderItem extends Eloquent {
use SoftDeletingTrait;
protected $dates = ['deleted_at'];
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'print_order_items';
protected $fillable = array( 'print_order_id', 'upload_id', 'size_id', 'quantity', 'created_at', 'updated_at', 'deleted_at' );
public function image() {
return $this->hasOne('Upload','id');
}
public function size() {
return $this->hasOne('PrintSize', 'id');
}
}
Upload.php
use Illuminate\Database\Eloquent\SoftDeletingTrait;
class Upload extends Eloquent {
use SoftDeletingTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'uploads';
protected $fillable = array( 'user_id', 'project_id', 'thumbnail', 'small','medium','large','original','title', 'description','keywords', 'file_type','file_size','file_extension','created_at', 'updated_at', 'deleted_at' );
protected $dates = ['deleted_at'];
public function categories() {
return $this->belongsToMany('UploadCategory', 'upload_image_categorys');
}
}
PrintSize.php
use Illuminate\Database\Eloquent\SoftDeletingTrait;
class PrintSize extends Eloquent {
use SoftDeletingTrait;
protected $dates = ['deleted_at'];
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'print_sizes';
protected $fillable = array( 'title', 'description', 'cost_actual', 'cost_client', 'status', 'created_at', 'updated_at', 'deleted_at' );
}

Categories