Cannot override laravel default auth username method - laravel

Laravel Framework 5.6.38
I am trying to change the default username auth check from 'email' to 'id',
So i put the username() method inside User model file to override the default username method
<?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 = [
'name', 'email', 'password','id'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function username()
{
return 'id';
}
}
It's not working with me . unless i change it from laravel vendor file
Illuminate\Foundation\Auth\AuthenticatesUsers.php
/**
* Get the login username to be used by the controller.
*
* #return string
*/
public function username()
{
return 'kocid';
}
The login now working but when i run composer update , the file return to it default, so i need a solution to successfully override this method using User model.

According to the documentation, https://laravel.com/docs/5.6/authentication#authentication-quickstart...you should do that in your LoginController
public function username()
{
return 'id';
}

Add the username method to your LoginController to override the method from the AuthenticatesUsers trait (Docs - Username Customization).
public function username()
{
return 'id';
}

Related

How can I fix User model in Laravel?

I have a custom User model in laravel. But I get errors when relationships with the User model. I couldn't find a similar problem on the internet. I have no idea what to do.
There was no User model before. I was using a model called Account and it was fine. But I updated the model name to User to use laravel's own Auth system.
Error:
Symfony\Component\ErrorHandler\Error\FatalError
Class Illuminate\Database\Eloquent\Relations\BelongsTo contains 6 abstract methods and must therefore be declared abstract or implement the remaining methods (Illuminate\Contracts\Auth\Authenticatable::getAuthIdentifierName, Illuminate\Contracts\Auth\Authenticatable::getAuthIdentifier, Illuminate\Contracts\Auth\Authenticatable::getAuthPassword, ...)
\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Relations\BelongsTo.php:12
class BelongsTo extends Relation implements \Illuminate\Contracts\Auth\Authenticatable {
My User model
<?php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
class User extends Authenticatable {
use HasFactory;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'full_name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* #var string[]
*/
protected $hidden = [
'password',
];
/**
* Get the blog posts for the user.
* #return HasMany
*/
public function posts(): HasMany {
return $this->hasMany(BlogPost::class, 'id', 'author_id');
}
}
BlogPost model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class BlogPost extends Model {
use HasFactory;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'author_id',
'thumbnail_id',
'title',
'slug',
'content',
'description',
'views',
];
/**
* Get the author for the blog post.
* #return BelongsTo
*/
public function author(): BelongsTo {
return $this->belongsTo(User::class, 'author_id', 'id');
}
}
users table migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up() {
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('full_name', 64);
$table->string('email', 64)->unique();
$table->string('password');
$table->softDeletes();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down() {
Schema::dropIfExists('users');
}
}
Try adding the Authorizable Trait to the User Model. Don't forget to add the use in too
use Illuminate\Foundation\Auth\Access\Authorizable;
class User extends Authenticatable
{
use Notifiable, Authorizable;

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.

Print user group name with Auth::User()->user_group->name in 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

Resources