I am getting a users details in a Laravel 5.5 controller like this...
$user = Auth::user();
But I want to do a check and see if the user has 'user_type' set to 'admin'
I know I can do a further check once I have the users info but is there a way to combine this into the one statement?
Create a method in User model:
public function isAdmin()
{
return $this->user_type === 'admin';
}
Then use it anywhere in your code:
if (auth()->user()->isAdmin())
Or just do it manually each time:
if (auth()->check() && auth()->user()->user_type === 'admin')
You can even create a global helper and do this:
#if (isAdmin())
This way you can retrieve the user_type of the authenticated user:
$user = Auth::user()->user_type;
As you can see here, the default migration for users does not have a user_type. Hence, if you want to give users certain privileges, you'll have to create it first.
I recommand using a out-of-the-box package. You can (for example) use the package laravel permissions and roles (by Spatie) to do the work for you.
Related
I am new to Laravel so please be patient with me.
i have to implement search functionality in Laravel. i am able to send form data to the search controller and receiving it as well
public function search_results(Request $request){
if ($request->has('gender')) {
echo $request->gender;
}
.....
}
Now when i am following tutorials on the web i am getting such examples :
public function filter(Request $request, User $user)
{
// Search for a user based on their name.
if ($request->has('name')) {
$user->where('name', $request->input('name'))->get();
}
}
or
public function index()
{
$users = User::where('status', 1)
->where('is_banned', 0)
->get(['name']);
dd($users);
}
now i am not sure from where this User:: or User $user is being added, and what should i do in my scenario.
Your suggestions would be helpful ..
Thanks
The $user represents an object belonging to the model(User::) associated with a table(users) in the mvc structure. If you want to "Search for a user based on their name." That means you already have a users table in database , and a User model .
You can use eloquent queries to retrieve data from database.
A User.php file should be generated when you create a new laravel project with composer. You can check for that.
So when you declare a variable like this :
$user = User::first();
You are actually getting the first element in 'users' table by using your User model.
If you can configure your User model and users table correctly , you should be able to get all records from your users table like this :
$users = User::all();
Then you can filter it like :
$users = $users->where('gender','male') // where('gender',$request->gender) in your situation
If you dont have a users table or a model , you can look to the document about how to create models using artisan commands Laravel API Doc. Generating Model Classes
I am using backpack to created admin panel in my project. I have two types of user one is Superadmin and second is admin. I just wanted to give the permissions to superadmin as he can list,add,edit all the rows from database..
but the admin can only edit,delete and list those rows created by himself..
So please help me, I am new in laravel backpack??
Filter the results you show in the setup() method of your entity's CrudController, then disallow access to update/destroy methods.
You result could look something like this:
public function setup()
{
// take care of LIST operations
if (\Auth::user()->hasRole('admin')) {
$this->crud->addClause('where', 'author_id', '=', \Auth::user()->id);
}
}
Additionally, you need to place checks inside your update() and destroy() methods, to not allow an admin to delete someone else's entry.
// place this both inside your update() and inside your destroy() method
if (\Auth::user()->hasRole('admin') && $this->crud->entry->author_id!=\Auth::user()->id) {
abort(405);
}
Hope it helps.
I have a user column in database which have viewed_at column with type date.
I want to update that field on every user login.
I wish to run the code on every user login --
$user = User::find(Auth::user()->id);
$user->viewed_at = /* current date */;
$user->save();
Please help me with this issue.
Please don't suggest me to do it in controller to which the authenticated person is redirected to.
The Auth class provides a handful of useful events. One of them is Login.
Listen to this event and update the $user->viewed_at when it's triggered.
In 5.3 you can override authenticated() method in Auth\LoginController.php and put the logic there. Also since Laravel always gets an instance of an authenticated user, you could save one query by using auth()->user() object.
use Carbon\Carbon;
....
protected function authenticated()
{
$user = auth()->user();
$user->viewed_at = Carbon::now();
$user->save();
}
Try:
$user->viewed_at = date('Y-m-d H:i:s');
When testing I am able to create a model factory and then act as that user e.g.
$users = factory(User::class)->create();
$this->actingAs($users)
Would it be possible for me to act as a user who is already in the database, so say I could reference their ID number and then test as that user?
Try $users = User::find(1); .. where 1 is the correct id.
You can use any Eloquent function such as User::where('name', '=', 'John'); too.
You might have to fix the User namespace like $users = App\Models\User::find(1); or use (import) it.
Note that you can roll back your databases after each test too, or simply use another database altogether.
How to get user role in Yii2?
I searched and read Yii2 guide but I didn't find any solution.
You can get Roles for an user by using getRolesByUser function
You can use it like this
\Yii::$app->authManager->getRolesByUser($user_id);
You can use:
Yii::$app->authManager->getRolesByUser(Yii::$app->user->getId());
I use :
if (\Yii::$app->authManager-> getAssignment($role,$rule_id))
for filtering user id and role in rbac, More details on Yii2 Documentation
One more example how to get user role:
Yii::$app->getUser()->identity->role;
It works if you have column with name "role" in your user table.
You can use :
$user =[];
$userAssigned = Yii::$app->authManager->getAssignments(user_id);
foreach($userAssigned as $userAssign){
$user[] = $userAssign->roleName;
}
If you're using amnah/yii2-user module, you can use this:
Yii::$app->user->identity->role->name
It will give you the current user role name
The good and more visual decision will be setting constants of all roles.
$userID = $user->getId();
array_keys(Yii::$app->authManager->getRolesByUser($userID))[0] == User::ROLE_NAME
You can get role of the user by using createcommand.
$roleModel = Yii::$app->db
->createCommand("Select * from auth_assignment where user_id='889'")
->queryOne();
echo $roleModel['item_name'];
This will you user's role in auth assignment. Now you can check that if user is admin or editor or member.