Laravel entrust return user with roles - php

Am using Zizaco entrust package and trying to get all users together with their roles
User model i have
use Laravel\Passport\HasApiTokens;
use Illuminate\Database\Eloquent\Model;
use Zizaco\Entrust\Traits\EntrustUserTrait;
class User extends Model implements AuthenticatableContract
{
use Authenticatable,HasApiTokens, EntrustUserTrait;
protected $fillable = [
'name', 'email', 'password','status'
];
protected $hidden = [
'password', 'remember_token',
];
public function role()
{
return $this->belongsTo('App\Role', 'id');
}
}
Now the App\Role
use Zizaco\Entrust\EntrustRole;
class Role extends EntrustRole
{
}
Whenver i fetch my users with
$sortval = explode("|",$request->sort);
return \App\User::orderBy( $sortval[0], $sortval[1])
->with("role") //added the relationship
->paginate($request->per_page);
The above role always returns null even when there are assigned roles to users.

Related

Change cashier model from User to Hotel

I want to use another model for cashier, not the default. I have 2 tables User and Hotel relation one-to-many (a user can have multiple hotels). I want to add possibility that a user can add different payment methods for his hotels. I removed cashier columns from user and I added to hotel table.
I put in services.php :
'stripe' => [
'model' => \App\Models\Hotel::class,
'key' => env('STRIPE_KEY'),
'secret' => env('STRIPE_SECRET'),
],
In my controller :
public function get(Request $request)
{
$creditorId = config('id');
$user = $request->user();
$stripeUser = $user->createOrGetStripeCustomer();
.............
}
I added in Hotel.php Billable and I removed Billable from User.
Now I have the error :
Call to undefined method App\Models\User::createOrGetStripeCustomer()
In the past was working for User.php. How can I fix this error?
User.php :
class User extends Authenticatable implements CanResetPassword {
use Notifiable, HasSanctumTokens, HasFactory;
protected $fillable = [
'email',
'password',
'lang',
];
.......
Hotel.php :
class Hotel extends Model
{
use Billable, HasFactory;
public $incrementing = false;
protected $fillable = [
'id',
'name',
'user_id',
];
.............
This error appears because you remove the Billable trait from your User model and moved it to the Hotel model
so what do you need to do from the model relation in this case (one -> many)
User Model
class User extends Authenticatable implements CanResetPassword {
use Notifiable, HasSanctumTokens, HasFactory;
protected $fillable = [
'email',
'password',
'lang',
];
public function hotels()
{
return $this->hasMany(Hotel::class);
}
after that from the controller you need to pass the hotel as a parameter instead of user
Controller
public function get(Request $request, Hotel $hotel)
{
$stripeUser = $hotel->createOrGetStripeCustomer();
.............
}

Laravel Models One to Many relation is not being established

I am doing a learning project. very new to Laravel. So I have a User and a Company profile CRUD. Company belongsTo User and User may have many Company. So in my User model I implemented this
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use App\Company;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'first_name', 'last_name', 'username', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
//relation with company
public function company(){
return $this->hasMany('App\Company','id');
}
}
and in company model i did
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Company extends Model
{
//table name
protected $table='companies';
//primary keys
protected $primaryKey='id';
//relation with User Model
public function user(){
return $this->belongsTo(App\Models\User::class);
}
My company profile controller is
public function index()
{
//Showing companies under user
$user_id = auth()->user()->id;
$user = User::find($user_id);
$companies=$user->company;
return view('company.profile')->with('companies', $companies);
}
But when it comes to execution, it seems like
public function user(){
return $this->belongsTo(App\Models\User::class);
}
this function in Company model is not working. I mean a company is getting assigned to one user but it should be like many companies in one user. What did I do wrong?
Btw my User model location is App/Model/User.php, and I declared the user model path in auth.php .My Company.php Model location is App/Company.php. please have a look and try to help this newb out. Many thanks.
i don't understand your question but my answer may be help you
users belongs to company
in model user
public function company()
{
return $this->belongsTo('App\Company');
}
maby be wrong code
//relation with company
public function company(){
return $this->hasMany('App\Company','id'); // not Id foreign_key as company_id
}
this is true but you can write it better as
public function index()
{
$user_id = auth()->user()->id;
$user = User::find($user_id)->with('company');
//$companies=$user->company;
return view('company.profile', compact('user');
}

Passing second user model data to a controller in Laravel

So I have 2 User models, one is User and other is OrgUser for company users.
I'm trying to pass OrgUser to a OrgUserController and display single company user in show method. But I always get an empty object.
User Model
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'email', 'password', 'verified', 'verification_token',
];
protected $hidden = [
'password', 'remember_token', 'verification_token',
];
OrgUser Model
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class OrgUser extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'email', 'password', 'verified', 'verification_token', 'admin'
];
protected $hidden = [
'password', 'remember_token', 'verification_token',
];
OrgUserController
<?php
namespace App\Http\Controllers\OrgUser;
use App\Http\Resources\OrgUserResource;
use App\OrgUser;
use Illuminate\Http\Request;
use App\Http\Controllers\ApiController;
class OrgUserController extends ApiController
{
public function show(OrgUser $orgUser)
{
// OrgUserResource::withoutWrapping();
//
// return new OrgUserResource($orgUser);
return $orgUser;
}
Routes
Route::resource('orgusers', 'OrgUser\OrgUserController', ['only' => ['index', 'show']]);
Is there something that I would need to add to OrgUser model so I could pass data to controller like that? Because it works if I pass $id.
So It seems the problem was with naming in show method. I need to pass $orguser and not $orgUser. Because in my route it was /orgusers/{orguser}.
The show function should be accepting the $id rather than the model. If you change your code to the following, it should work:
public function show(Request $request, $id)
{
$orgUser = OrgUser::find($id);
return $orgUser;
}

How to fetch username from other table user_id store in other table

I have a table "articles" in this table a column name "user_id", I have another table "users" where store username, profile_pic etc... I want to fetch username on home page where I already fetched articles title.
Article Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
public function category()
{
return $this->belongsTo('App\Category');
}
public function tags()
{
return $this->belongsToMany('App\Tag');
}
}
View Page(Home Page)
{{$article->user_id}}
Here I want to Display username
User Model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
}
Add the following to Article class:
public function user() {
return $this->belongsTo(User::class);
}
Then you can access related user data with $article->user->name

laravel relationship's tables

I have 4 tables:
user(id,role_id)
role(id)
permission_role(role_id,permission_id)
permission(id, name)
User model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Zizaco\Entrust\Traits\EntrustUserTrait;
class User extends Authenticatable
{
use Notifiable;
use EntrustUserTrait;
/**
* 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 roles()
{
return $this->hasOne('App\Role', 'id', 'role_id');
}
}
Role model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Zizaco\Entrust\EntrustRole;
class Role extends EntrustRole
{
public function users()
{
return $this->belongsTo('App\User','role_id','id');
}
public function permissions()
{
return $this->belongsToMany('App\Permission','permission_role');
}
}
Permission model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Zizaco\Entrust\EntrustPermission;
class Permission extends EntrustPermission
{
public function roles()
{
return $this->belongsToMany('App\Role','permission_role');
}
}
and i want to test in my controller to see if user have permission delete_article via if condition, any help? and thanks
In you Role model
Something like this you need to do (Many to Many)
//.......................
public function permissions()
{
return $this->belongsToMany('App\Permission','permission_role''role_id', 'permission_id');
}
//......................
See Many to Many relationship: Link
And to get the data into your controller
//..........................................
$user = get data with role and permission
$roles= $user->roles;
foreach($roles as $role){
foreach($role->permissions as $permission){
$permissiona_name = $permission->name;
}
}
//...........................
first check with var_dump($user)
Many to many with pivot (see Retrieving Intermediate Table Columns section)
return $this->belongsToMany('App\Role')->withPivot('column1', 'column2');
See also "Has Many Through"

Categories