Default User model and Relatinship - Laravel 5.4 - php

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();

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();

laravel 5.3 error : Trying to get property of non-object

Laravel 5.3
I am trying to get the fields from tables users and mobiles
users table has a primary key id
and my mobiles tables has a field users_id
so I want to get all the numbers of all users_id
select u.*,m.mobile,ud.name from users u
left join userdetails ud on ud.user_id = u.id
left join mobiles m on m.users_id = u.id
where m.mobiletypes_id = 1 and m.deleted_by is null
I am trying the above query in eloquent but I am facing an error
undefined property illuminate database eloquent collection
my user model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'email', 'password','role_id'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function mobile()
{
return $this->hasMany('App\mobile','users_id');
}
public function userdetails()
{
return $this->hasOne('App\Userdetails');
}
}
my mobile model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class mobile extends Model
{
protected $primaryKey = 'mobiles_id';
protected $fillable = ['mobile', 'mobiletypes_id', 'users_id', 'created_by', 'updated_by', 'deleted_by', 'created_at', 'updated_at'];
}
my controller
public function employeeview(){
// $user = User::all(); // get all user
$userdetails = User::with(['mobile' => function ($query) {
$query->where('mobiletypes_id', 1);
} ,'userdetails'])->get(); // get all userdetails
// $mobile = User::with('mobile')->get();
//$userdetails = User::all();
//return $user;
//return view('employeeview',compact('userdetails'));
return view('employeeview')->with('userdetails', $userdetails);
}
my view employeeview.blade.php
#foreach($userdetails as $u)
<tr>
<td>{{$u->id}} </td>
<td>{{$u->userdetails->name}} </td>
<td>{{$u->email}}</td>
#foreach($u->mobile as $um)
<td>{{$um->mobile}}</td>
#endforeach
</tr>
#endforeach
I would first advise to place a dd($userdetails) before the return of the view, in order to check that it is indeed what you're looking for.
If needed, create a variable called
$visible = []
and place all the visible fields inside it.

Conditional menu items based on User Role

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;
}
}
}

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.

How to retrive userID from users table?

I have a two table named users and profile . In profile table there is a column named userID.Now i want to this userID column takes value from users table's id.I have done database relationships part.But can not retrieve data with view.I have searched but i have not found any satisfying answer according my issue.
By the way i am new in Laravel.I have tried so far
User Model:
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $table ="users";
protected $fillable = [
'userName', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function userProfile(){
return $this->hasOne('App\Profile');
}
}
Profile Model:
class Profile extends Model
{
//
protected $table = "profiles";
public $fillable = ["firstName","lastName","middleName","DOB","gender","featuredProfile","email","phone","summary","profilePic"];
public function user(){
return $this->belongsTo('App\User');
}
}
And i am trying to retrieve userID with {{$profile->userID}}.I really don't know where is the problem and how to do this?
you will need to tell laravel to get the relationship model like this
$profile = Profile::find(1);
$userID = $profile->user->id;
edit:
from the docs
model is automatically assumed to have a user_id foreign key.
which in your case is userId so change your hasOne and belongsTo methods to tell laravel the name of foreign_key you are using
public function profile()
{
return $this->hasOne('App\Profile', 'userId');
}
public function user()
{
return $this->belongsTo('App\User', 'userId');
}
Please add userID to the fillable array of profiles.
Please check below sample code to do the same.
public $fillable = ["firstName","lastName","middleName","DOB","gender","featuredProfile","email","phone","summary","profilePic","userID"];

Categories