Laravel - How to get Entrust Roles of a specific user - php

I'm making a small work with Laravel and using Zizaco Entrust.
While logged in as Administrator I want to see all Roles of a specific user.
I'v searched for a while but didn't find any clue...
How can I do it using Entrust or shall I use SQL queries?

In your User class add
public function roles()
{
return $this->belongsToMany('Role','assigned_roles');
}
Then you can get all roles for a specific user
$user = User::with('roles')->find(1);
$roles = $user->roles;

If you are using Zizaco\Entrust you don't need new roles method in User model. Roles method already exist in EntrustUserTrait class. You only need this line inside User class:
use EntrustUserTrait;
like this:
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Zizaco\Entrust\Traits\EntrustUserTrait;
class User extends Authenticatable
{
use EntrustUserTrait; // add this trait to your user model
.....
}
In your UsersController you can select users with their roles (index method):
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use App\Http\Requests;
class UsersController extends Controller
{
protected $users;
public function __construct(User $users)
{
$this->users = $users;
parent::__construct();
}
public function index()
{
$users = $this->users->with('roles')->paginate(25);
return view('users.index', compact('users'));
}
In your blade loop $user->roles inside $users loop because $user->roles are collection even if user have only one role.
#foreach($users as $user)
#foreach($user->roles as $role)
{{ $role->display_name }}
#endforeach
#endforeach

Related

Property [posts] does not exist on this collection instance

Hope you're all having a good day. I'm working on a blogs page and reached a part where I want to display the certain blogs a user has posted. I added relations to the Post model and User model but i can't seem to get the specific posts of the logged in user and it gives me the error above in the title. Here are my models and Profile controller.
The users schemaThe posts schema
Post model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function user(){
return $this->belongsTo('App\User');
}
}
Posts function in User model
public function posts(){
return $this->hasMany(Post::class);
}
The ProfileController
<?php
namespace App\Http\Controllers;
use App\Reviews;
use Illuminate\Foundation\Auth\User;
use Illuminate\Http\Request;
class ProfileController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$user_id=auth()->user()->id;
$user = User::where('id', $user_id)->get();
$posts= $user->posts;//Gets all details of the user with id 123
return view('profile')->with(['users' => $user ],['posts', $posts]);
}
}
$user = User::where('id', $user_id)->get(); // return a collection so it is multiple items and would have to be accessed as so
This should be
$user = User::where('id', $user_id)->first();
Or rather
$user = User::find($user_id);
But better
$user = auth()->user()
Be mindful that you are doing some unnecessary work, auth()->user() is the user instance there is no need to use that to then get it from the database. As it stands you would have access to the User in the blade template for profile using Auth::user() So there may be no reason just yet to even do any database queries in the controller. This may change as you build out the page of course

Lavarel - Error in relation: Call to undefined relationship [nota] on model [App\Nota]

I want to make the following query with Eloquent:
$nota=DB::table('notas')
->join('users', 'users.id', '=', 'notas.id_user')
->select('notas.id','notas.nombre', 'notas.descripcion', 'users.name AS user_name', 'users.email')
->first();
I try to make the relation in the models and called like this, in my controller:
public function show($id)
{
$nota = Nota::with(['user','nota'])->first();
print_r($nota);
return view("notas.detalle", compact("nota"));
}
But i get the follow error:
Illuminate\Database\Eloquent\RelationNotFoundException
Call to undefined relationship [nota] on model [App\Nota].
My models looks like this:
Nota.php:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Nota extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
}
User.php:
<?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;
public function notas()
{
return $this->hasMany('App\Nota');
}
}
The problem is with your understanding of relationship. You don't make any relationship named nota but you are using it and ridiculously with the same model. So firstly make the relationship right using naming convention.
In Nota model
public function user()
{
return $this->belongsTo('App\User','id_user');
}
In User model
public function notas()
{
return $this->hasMany('App\Nota','id_user');
}
And now in controller
$nota = Nota::with('user')->first();
return view("notas.detalle", compact("nota"));
Look this is an eager loading. You can lazy load the relationship too.
In view now you can access object property like
{{ $nota->nombre }}
And relationship object like
{{ $nota->user->email }}
The problem is with this function Nota::with(['user','nota'])->first()
Why do you want nota with nota. it's sounds ridiculous isn't it?
So just remove it, then everything will work fine.
$nota = Nota::with(['user'])->first();
return view("notas.detalle", compact("nota"));

Paginate data from relationship model in Laravel

Apologies if the title doesn't completely make sense... I wasn't sure if the exact terminology for the linking of models are the associated data in their controllers.
I'm trying to paginate a table with the posts created by a user.
I managed to paginate it previously, without the user_id in the posts table. But I've added the user_id to the posts table, and run the migration which works fine.
The following is my Post model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function user(){
return $this->belongsTo('App\User');
}
}
And this is my 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',];
protected $hidden = ['password', 'remember_token',];
public function posts() {
return $this->hasMany('App\Post');
}
}
And this is the relevant section of the post controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
use App\User;
use Session;
use Carbon\Carbon;
class PostController extends Controller
{
public function index()
{
$user_id = auth()->user()->id;
$user = User::find($user_id);
return view('posts.index')->with('posts', $user->posts);
}
I thought that it would simply be a case of appending ->paginate(5) to the $user in the PostController, but that doesn't appear to work.
I get the following:
Undefined property: Illuminate\Pagination\LengthAwarePaginator::$posts
I've tried including the {!! $posts->links() !!} in the posts.index view before the #foreach but that gives:
Undefined property: Illuminate\Pagination\LengthAwarePaginator::$posts
I'm trying to learn Laravel basics by creating this crud application, and have tried combining two tutorials together, but I'm clearly missing something.
You can call ->paginate() on the relationship like this (also I've removed the unnecessary user query, since auth()->user() will execute it already):
public function index()
{
$user = auth()->user();
$posts = $user->posts()->paginate();
// Or with 1 line: $posts = auth()->user()->posts()->paginate();
return view('posts.index')->with('posts', $posts);
}

Laravel 5.2 : How to get the role of current user when using `Zizaco/entrust`?

I am using Laravel 5.2 and Zizaco/entrust 5.2,my question is:
How to get the role of current user when using Zizaco/entrust?
NameAndRole.php
namespace App\Services;
use App\User;
use App\Role;
use Zizaco\Entrust\EntrustRole;
use Illuminate\Support\Facades\Cache;
class NameAndRole
{
public $username;
public $role;
public function __construct() {
$user = \Auth::user();
$this->username = $user->name;
$this->role =$user->roles->first()->name;
}
}
Models:
Role:https://github.com/Zizaco/entrust#role
<?php namespace App;
use Zizaco\Entrust\EntrustRole;
class Role extends EntrustRole
{
}
User:https://github.com/Zizaco/entrust#user
<?php
use Zizaco\Entrust\Traits\EntrustUserTrait;
class User extends Eloquent
{
use EntrustUserTrait; // add this trait to your user model
...
}
view: sidebar.blade.php
#inject('details','App\Services\NameAndRole')
{{ $details->username }}
{{ $details->role }}
error:
ErrorException in NameAndRole.php line 20:
Trying to get property of non-object (View: D:\wnmp\www\laravel-entrust\resources\views\employer\partials\sidebar.blade.php) (View: D:\wnmp\www\laravel-entrust\resources\views\employer\partials\sidebar.blade.php)
You can access it like any other relationship in eloquent. So to access the roles of a user you can do:
$user->roles
This returns an eloquent collection as a User can have many Roles (i.e. it won't be just one), so if you're only expecting one role and you want the string value of it, you could do:
$user->roles->first()->name // or display_name
I guess you could cast it to an array using toArray() method, if you wanted to work with an array instead:
$user->roles->toArray()
Edit
You could check the user has a role before assigning it:
$this->role = $user->roles ? $user->roles->first()->name : 'No role';
To get the roles id field:
$user->roles->first()->id;

Laravel 5 check role giving error "trying to get property of non object"

I am very new to Laravel and am trying to implement roles to users.
I have created the Role table and Model associated with it
I have added a column role to the users table.
I am now trying to check that role in the User model
EDIT: After an answer/explanation here I changed role to role_id in the users table but I am still getting the same error.
Here is my User Model...
<?php namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Auth;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
// more stuff
public function role()
{
return $this->belongsTo('App\Role');
}
public function isAdmin()
{
return $this->role->slug == 'admin';
}
}
And my Role Model
<?php namespace App;
use Illuminate\Database\Eloquent\Model as Eloquent;
class Role extends Eloquent {
protected $table = 'roles';
public function users()
{
return $this->hasMany('App\User');
}
}
When I go to my admin page I have the following function...
public function index(User $user)
{
if ($user->isAdmin()) {
return view('admin/home_admin');
}
else {
return redirect('home');
}
}
However Im getting the error...
Trying to get property of non-object in User.php line 62 at
HandleExceptions->handleError('8', 'Trying to get property of
non-object', '/home/vagrant/Code/esearch/app/User.php', '62', array())
in User.php line 62
I have tried this while logged in and not logged in with the correct role. Am I missing something obvious here?
The problem with the code started off with the role_id setting that #user3158900 noticed. This was something that needed to be resolved.
But you were using the improper form of user when attempting to see what is happening. Instead of the User $user you need Guard $user or Guard $auth as it is more commonly seen. You can also use Auth::user()->isAdmin().
There is one last thing that should be looked at that I did not mention in my comment above.
If the user is not logged in and is a guest you will get an error trying to find Auth::user() and it will fail. This is because Auth::user() is null when you are a guest. So you should do a check that is logged in.
You can either use !Auth::guest() or Auth:check() (which is cleaner).
Hopefully this is all good for you!
You are close. Laravel assumes the foreign key for role to be role_id but since you are using role, you need to set that up in your relation as well.
In your Role model.
public function users()
{
return $this->hasMany('App\User', 'role');
}
In your User model.
public function role()
{
return $this->belongsTo('App\Role', 'role');
}
Because role would both be a relating function and a column in your table, it would be best to modify the column name to role_id to match what Laravel expects.

Categories