Print user group name with Auth::User()->user_group->name in Laravel 4 - laravel-4

I'm trying to display the user group name in a view using Auth::user()->user_group->name, but apparently that doesn't work as I keep getting Trying to get property of non-object.
The code goes as follow
User_Group.php Model
<?php
class User_Group extends Eloquent {
protected $table = 'user_groups';
public function users() {
return $this->hasMany('User');
}
}
User.php Model
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
public function user_group()
{
return $this->belongsTo('User_Group', 'user_groups_id');
}
public function getGravatarAttribute()
{
$hash = md5(strtolower(trim($this->attributes['email'])));
return "http://www.gravatar.com/avatar/$hash?s=100";
}
public function isAdmin()
{
return $this->user_groups_id == 1;
}
}
My profile.blade.php view
<small><p class="pull-right">{{ Auth::user()->user_group->name }}</p></small>
Doing the following will print the user group id reference though:
{{ Auth::user()->user_groups_id }}

Rename the method to group instead of user_group

Related

Display 2 types of data in Laravel

I have 2 types of user Athletes and Teams. I created 3 tables users,athletes & teams. I am storing username & password in users table and others information in athletes & teams table. I would like to display Athletes and Teams information in home page.
My User model is like below
<?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 $guarded = [];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = ['password', 'remember_token',];
protected $fillable = ['email','password','remember_token','category_id'];
public function team()
{
return $this->hasOne(Team::class);
}
public function athlete()
{
return $this->hasOne(Athlete::class);
}
}
My Team model is like below
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Team extends Model
{
public $guarded = [];
protected $fillable = ['first_name','last_name','user_id','how_did_find','social_media',];
public function user()
{
return $this->belongsTo(User::class);
}
}
My Athlete model is like below
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Athlete extends Model
{
public $guarded = [];
protected $fillable = ['user_id','social_media','youtube_video','website'];
public function user()
{
return $this->belongsTo(User::class);
}
}
I am using below code in controller.
$staff_picks = User::orderBy('id','desc')->take(10)->with('athlete','team')->get();
This is how it should be
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $guarded = [];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = ['password', 'remember_token',];
protected $fillable = ['email','password','remember_token','category_id'];
public function team()
{
return $this->hasOne(Team::class);
}
public function athlete()
{
return $this->hasOne(Athlete::class);
}
}
class Team extends Model
{
public $guarded = [];
protected $fillable = ['first_name','last_name','user_id','how_did_find','social_media',];
public function user()
{
return $this->belongsTo(User::class);
}
}
class Athlete extends Model
{
public $guarded = [];
protected $fillable = ['user_id','social_media','youtube_video','website'];
public function user()
{
return $this->belongsTo(User::class);
}
}
And the query
$staff_picks = User::orderBy('id','desc')->take(10)->with('athlete','team')->get();
And the iteration
foreach($staff_picks as $r){
$r->teams->social_media; //(user can be either teams or athletes so must check for null)
$r->athletes->social_media; //(user can be either teams or athletes so must check for null)
}
In athlete & team model create a column called user_id and in user model create two methods as hasMany relation for athletes and teams models.
After login get the data as
User::where('id', 1)->with('teams', 'athletes')->first();
Relations inside User modal can be written as below.
teams() {
return $this->hasMany(Team::class);
}
athletes() {
return $this->hasMany(Athlete::class);
}

Eloquent model inheritance hierarchy

I have a case where 2 eloquent models should inherit properties from a User model, but the User itself should not exist as a standalone instance. (Mentors and Students, both inherit from User class). So what I'm currently doing is:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
abstract 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',
];
/**
* Get the courses that the user has enrolled into
*
* #return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function courses()
{
return $this->hasMany('App\Models\Course', 'user_course', 'user_id', 'course_id');
}
}
class Student extends User
{
protected $table = 'students';
/**
* Get the mentors that the user has hired
*
* #return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function mentors()
{
return $this->hasMany('App\Models\User');
}
}
class Mentor extends User
{
protected $table = 'mentors';
/**
* Get a list of courses that a mentor is teaching
*
* #return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function ownCourses()
{
return $this->hasMany('App\Models\Course', 'mentor_course', 'mentor_id', 'course_id');
}
}
I am wondering whether this is the correct to do what I am trying to accomplish?
IMHO I will use polymorhic relation:
Use three tables: users, students and mentors; in the users table add two fields: userable_id (integer), userable_type (string).
User model
class class User extends Authenticatable
{
public function userable()
{
return $this->morphTo();
}
Student model:
class Student extends Model
{
public function user()
{
return $this->morphOne('App\User', 'userable');
}
Mentor model:
class Mentor extends Model
{
public function user()
{
return $this->morphOne('App\User', 'userable');
}
Now User::find($id)->userable return a Student or a Mentor object depending on the value of the userable_type
I leave the others relations to you, I hope this helps.

ReflectionException in CommanderTrait.php line 59: Class App\FollowUserCommand does not exist

I Was following Laracasts video for creating follow option but when I'm clicking on Follow button on members page it is showing the above error. This is my followcontroller
<?php
namespace App\Http\Controllers;
use App\User;
use Laracasts\Commander\CommanderTrait;
use App\FollowUserCommand;
use Sentinel;
use Illuminate\Support\Facades\Input;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class FollowsController extends Controller
{
use CommanderTrait;
/**
* Follow a User
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store()
{
$input = array_add(Input::all(), 'user_id', Sentinel::getuser()->id);
$this->execute(FollowUserCommand::class, $input);
return Redirect::back();
}
/**
* Unfollow a User
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
This is my FollowUserCommand
<?php namespace App\User;
class FollowUserCommand {
public $user_id;
public $userIdToFollow;
function __construct($user_id, $userIdToFollow)
{
$this->user_id = $user_id;
$this->userIdToFollow = $userIdToFollow;
}
}
FollowUserCommandHandler
<?php namespace App;
use Laracasts\Commander\CommandHandler;
class FollowUserCommandHandler implements CommandHandler {
protected $userRepo;
function __construct(UserRepository $userRepo)
{
$this->userRepo = $userRepo;
}
public function handle($command)
{
$user = $this->userRepo->findById($command->user_id);
$this->userRepo->follow($command->userIdToFollow, $user);
return $user;
}
}
UserRepository
class UserRepository {
public function save(User $user)
{
return $user->save();
}
public function getPaginated($howMany = 4)
{
return User::orderBy('first_name', 'asc')->paginate($howMany);
}
public function findByUsername($username)
{
return User::with(['feeds' => function($query)
{
$query->latest();
}
])->whereUsername($username)->first();
}
public function findById($id)
{
return User::findOrFail($id);
}
public function follow($userIdToFollow, User $user)
{
return $user->follows()->attach($userIdToFollow);
}
}
User.php
<?php namespace App;
use Cartalyst\Sentinel\Users\EloquentUser;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends EloquentUser {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes to be fillable from the model.
*
* A dirty hack to allow fields to be fillable by calling empty fillable array
*
* #var array
*/
protected $fillable = [];
protected $guarded = ['id'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
/**
* To allow soft deletes
*/
use SoftDeletes;
protected $dates = ['deleted_at'];
// This function allows us to get a list of users following us
public function follows()
{
return $this->belongsToMany(self::class, 'follows', 'follower_id', 'followed_id')->withTimestamps();
}
// Get all users we are following
public function following()
{
return $this->belongsToMany('User', 'followers', 'user_id', 'follow_id')->withTimestamps();
}
}
Can anyone tell me why it is showing error even after "use App\FollowUserCommand;" has been declared in namespace.
Your namespace when declaring the FollowUserCommand class is wrong, it should be:
<?php namespace App;
class FollowUserCommand {...
And right now you have <?php namespace App\User;.

Class Not Found - Eloquent

i have these two models:
<?php namespace App\Models;
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;
class User extends Model {
use Authenticatable, CanResetPassword;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['name', 'email', 'password', 'is_active'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
public function customer_details()
{
return $this->hasOne('CustomerDetails', 'user_id');
}
}
And:
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class CustomerDetails extends Model {
protected $table = 'customer_details';
public function user()
{
return $this->belongsTo('User');
}
}
Now i am trying to get all customers along with their user data from the database in my index() of my UserController():
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
$users = User::with('customer_details')->get();
return [
'users' => $users
];
}
But i keep getting this error:
Fatal Error Exception Class 'CustomerDetails' not found
I have no idea what i am doing wrong here.
Your class is namespaced and should therefore be referred to as App\Models\CustomerDetails, in the $this->hasOne(...) definition of customer_details of the App\Models\User model.

many-to-many relationschop in laravel eloquent does not work with pluck()

I have a many to many relationshhip between 2 tables in laravel.
I just want to get the name of the afdeling with user_id=45.
I tried
$afdelingen = User::find(45)->afdelingen->pluck('name');
but is does not work. It works without the pluck but then i get a long string:
[{"id":3,"afdelingen":"Personeelszaken","user_id":0,"pivot":{"user_id":45,"afdeling_id":3}}]
How can i just get
Model 1 code:
<?php
class Afdeling extends Eloquent {
protected $guarded = array();
public static $rules = array();
protected $connection = 'mysql2';
protected $table = 'afdelingen';
public function users(){
return $this->belongstoMany('User','afdeling_user','afdeling_id');
}
}
Model 2 code:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
/**
* The database table used by the model.
*
* #var string
*/
protected $connection = 'mysql2';
protected $table = 'users';
//public function safetyreports(){
// return $this->hasMany('Safetyreport');
//}
public function afdelingen(){
return $this->belongstoMany('Afdeling','afdeling_user','user_id');
}
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password');
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getReminderEmail()
{
return $this->email;
}
}
Since it's a many to many relationship, $afdelingen = User::find(45)->afdelingen->pluck('name'); will have a collection of afdelingen, not just one.
You can get the first one by using $afdelingen = User::find(45)->afdelingen()->first()->pluck('name');
Additionally, you can loop to grab all their names.
foreach(User::find(45)->afdelingen as $item) {
$afdelingen = $item->pluck('name');
}
Or if you want an array of the names...
$afdelingen = User::find(45)->afdelingen()->lists('name');

Resources