Conditional menu items based on User Role - php

I'm getting stuck on something that should be simple.
Using Laravel 5.3. I have a function setup for User::isAdmin() that can both check if a user has a given role.
I have some conditional menu items that should only appear for admins. how can I check for a role within a blade view file?
I have my many-to-many relationship setup and working fine for Users and Roles. When I try something along the lines of auth()->user()->isAdmin() or Auth::user()->isAdmin(), I get the following error:
Call to undefined method Illuminate\Auth\GenericUser::isAdmin()
Here's a copy of my User model:
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Role;
class User extends Authenticatable
{
// use SoftDeletes;
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'first_name', 'last_name', 'company', 'email', 'tax_id', 'address', 'city', 'state', 'zip', 'phone','password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function roles()
{
return $this->belongsToMany('App\Role');
}
/**
* Find specified user role by id or name
* #param [type] $uid user_id
* #param [type] $role either name or id
* #return boolean [description]
*/
static function hasRole($uid, $role){
$user = User::find($uid);
if(is_numeric($role)){
foreach ($user->roles as $r) {
// var_dump($r->id);
if($r->id == $role){
return true;
}
return false;
}
}else{
foreach ($user->roles as $r) {
if($r->name == $role){
return true;
}
return false;
}
}
}
public function isAdmin(){
$user = User::find(Auth::user()->id);
foreach ($user->roles as $r) {
if($r->id == 1){
return true;
}
return false;
}
}
}

Related

Laravel Auth Session Missing After Redirect(with web middleware)

im using laravel 7.14
I'm using laravel's Auth to do a login process and keep my application authenticated using username and password in my database. Here is my route:
Route::group(['middleware' => 'web'], function () {
Route::post('/user/login', 'UserController#loginUser');
});
and my login function
public function loginUser(Request $request)
{
$field = 'email';
if (is_numeric(Request()->username)) {
$field = 'mobile';
} elseif (filter_var(Request()->username, FILTER_VALIDATE_EMAIL)) {
$field = 'email';
}
if ($field == "mobile") {
$user = User::where("mobile",'=',Request()->username)->first();
}
else{
$user = User::where("email",'=',Request()->username)->first();
}
if($user){
Auth::login($user, Request()->filled('remember'));
$data = ["status" => true,"mobile_verified" => Auth::user()->mobile_verified];
return response($data)
->header("Access-Control-Allow-Origin", config('cors.allowed_origins'))
->header("Access-Control-Allow-Methods", config('cors.allowed_methods'));
}
else
{
$data = ["status" => false];
return response($data)
->header("Access-Control-Allow-Origin", config('cors.allowed_origins'))
->header("Access-Control-Allow-Methods", config('cors.allowed_methods'));
}
}
but after redirect i check Auth::guest() and it is true.
i searched a lot and solutions is use of web middleware but its not work for me
UPDATE:
My User Model Is:
<?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','family', 'email','mobile','tel','state','city','verification_code','district','address','role', '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',
];
}

laravel belongsTo on User Model not working

Following are my relations in laravel , I am unable to access company using User's Object, but i am getting null when i try to access it, please see my code below to get the picture
following are my models
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Zizaco\Entrust\Traits\EntrustUserTrait;
use Session;
use Illuminate\Support\Facades\DB;
class User extends Authenticatable
{
use Notifiable;
use EntrustUserTrait;
protected $table = 'tbl_users';
protected $primaryKey = 'id';
protected $guarded = ['id'];
const API = 'api';
const WEB = 'web';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'last_login', 'Address', 'Age', 'DateOfBirth', 'created_by', 'deleted_by'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'is_admin' => 'boolean',
];
public function isAdmin()
{
return $this->is_admin;
}
static function GetUserNamebyID($id)
{
$name = User::select("name")->where(["id" => $id])->pluck('name');
if (isset($name[0])) {
return $name[0];
} else {
return '';
}
}
public function loginlogout()
{
$this->hasMany("App\Models\LoginLogoutLogs", 'userID');
}
public function company()
{
$this->hasMany("App\Models\Company", "company_id");
}
}
And following is my companies Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use DB;
use App\Models\CarePlanData;
use Session;
class Company extends Model
{
protected $table = 'companies';
protected $primaryKey = 'id';
protected $guarded = ['id'];
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'phone_no', 'address', 'password', 'description', 'city', 'company_logo', 'country', 'email'
];
static public function fetchAllActiveCompanies()
{
return DB::table("companies")->where(['is_active' => 1])->pluck('name', 'id');
}
// change company to hasmany
public function users()
{
return $this->hasmany('App\Models\User');
}
}
and this is how i am trying to access the Company , but i am getting null.
public function fetchCompany(){
$User = User::find($user->id);
dd($User->company());
}
First of all if a user belongs to 1 company then it should be:
public function company()
{
$this->belongsTo("App\Models\Company", "company_id");
}
then fetchCompany() should be
public function fetchCompany(){
$User = User::with('company')->find($user->id);
dd($User->company);
}
You need to use with to load the relations. You pass the name of the function which defines the relation in your User model to with like this with('function_name').
Your actual question is:
You have belongTo Relation between User and Company but when you trying to access the Company via user object, you get null
In your User.php Model put the following function but if you already have then leave it:
public function company()
{
$this->belongsTo("App\Models\Company", "company_id");
}
Then
Replace this function:
public function fetchCompany(){
$User = User::find($user->id);
dd($User->company());
}
To is one:
public function fetchCompany(){
$User = User::find($user->id);
if($User){
dd($User->company()->get());
}
}
or to this one:
public function fetchCompany(){
$User = User::find($user->id);
if($User){
dd($User->company);
}
}
actually if your company_id field is on user model, then your relation should be
public function company()
{
$this->belongsTo("App\Models\Company", "company_id");
}
unless a user can have many companies ?

Default User model and Relatinship - Laravel 5.4

I use the default User model and I have created a UserStatus model:
User
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 status()
{
return $this->belongsTo('App\UserStatus');
}
}
UserStatus
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserStatus extends Model
{
public $timestamps = false;
public function users()
{
return $this->hasMany('App\User');
}
}
I cant access to the related model attribute because the $user->status is NULL:
$users = User::all();
foreach ($users as $user) {
var_dump($user->status->name);
}
What is the best practice/solution?
Thanks!
Your query will cause you the N+1 query problem.
Try this which is efficient
$users = User::with('status')->get();
foreach ($users as $user) {
logger($user->status->name);
}
There are two ways to approach:
Simply add a defense condition:
$users = User::all();
foreach ($users as $user) {
if(!empty($user->status))
var_dump($user->status->name);
}
You define a nullable column as user_status_id in your users table and make it foreign key for id in user_status table and create relationship in your User model : hasOne and give the foreign key and then only take users out which are having some status otherwise dont:
$users = User::whereNotNull('user_status_id')->get();

How to access other related model data in Laravel?

I am creating a user profile page and I want to retrieve the data from my User model and UserProfile model. But I have a problem in getting the result. Here's what I did:
User model
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'username',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/*
public function isAdmin() {
return $this->admin;
}
*/
public function profile() {
return $this->hasOne('App\UserProfile');
}
}
UserProfile model
class UserProfile extends Model
{
protected $table = 'user_profile';
protected $fillable = [
'phone',
'address'
];
public function user() {
return $this->belongsTo('App\User');
}
}
Then I access the relation in my ProfileController
public function getProfile($username) {
$user = User::with('user_profile')->where('username', $username)->get();
dd($user);
}
And I got this error:
Call to undefined relationship [user_profile] on model [App\User].
The user_profile is my table name
Use proper relationship name:
$user = User::with('profile')->where('username', $username)->first();
Also, in this case you should use the first() method to get an user object.

Call model function into custom middleware file in Laravel 5.2

I am new in Laravel. I am developing an application from scratch as of now I just used laravel auth i.e (php artisan make:auth).
My requirement is to pull data for a loggedin user from a table i.e "admin" into my custom middleware but I am unable to call function which is defined in my Model i.e "Admin" file.
MODEL FILE :- app\Admin.php
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Admin extends Authenticatable
{
/**
* 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->belongsToMany('App\Role', 'admin_role', 'admin_id', 'role_id');
}
public function hasAnyRole($roles)
{
if (is_array($roles)) {
foreach ($roles as $role) {
if ($this->hasRole($role)) {
return true;
}
}
} else {
if ($this->hasRole($roles)) {
return true;
}
}
return false;
}
public function hasRole($role)
{
if ($this->roles()->where('name', $role)->first()) {
return true;
}
return false;
}
public function myfunction($val)
{
echo "===>".$val; exit ;
}
}
MIDDLEWARE FILE :- app\Http\Middleware\CheckRole.php
<?php
namespace App\Http\Middleware;
use Closure;
class CheckRole
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$request->admin->myfunction('customvalue');
exit ;
}
}
I need to call function i.e "myfunction" which is define in Admin model into Checkrole.php middleware.
Thanks
try
auth()->user()->myfunction();
from the middleware. ( I am assuming you have an authenticated user at this point)

Categories