Can't assign Default User role to a new user - php

Error Message:
Call to undefined method App\User::roles()
I'm Tring to assign default role to new user But I failed to assigned it. All user information stored in database but Role can't stored in table. Where i mistaked in this code. Help me.My English not good, Sorry for miss-communication.
This is My Code of User.php, Role.php, RegisterController.php and HomeController.php Files. See and tell me "where i doing wrong?"
This is User.php File
namespace App;
use App\Role;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* #param string|array $roles
*/
public function authorizeRoles($roles)
{
if (is_array($roles)) {
return $this->hasAnyRole($roles) ||
abort(401, 'This action is unauthorized.');
}
return $this->hasRole($roles) ||
abort(401, 'This action is unauthorized.');
}
/**
* Check multiple roles
* #param array $roles
*/
public function hasAnyRole($roles)
{
return null !== $this->roles()->whereIn('name', $roles)->first();
}
/**
* Check one role
* #param string $role
*/
public function hasRole($role)
{
return null !== $this->roles()->where('name', $role)->first();
}
/**
* 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',
];
}
This is Role.php File
<?php
namespace App;
use App\User;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
public function users()
{
return $this->belongsToMany(User::class);
}
}
This RegisterController.php File.
<?php
namespace App\Http\Controllers\Auth;
use App\Role;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$user
->roles()
->attach(Role::where('name', 'student')->first());
return $user;
}
This is my role_user database Table
User Database Table
Role Database Table

Refactor your create method in RegisterController.php file like this:
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$user
->roles()
->attach(Role::where('name', 'student')->first());
return $user;
}
your rest of the code will not run after return.
and add roles relation to User model like this:
public function roles()
{
return $this->belongsToMany(User::class);
}

You can update your create function with this
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$role = new App\Role(['role' => 'student']);
$user->roles()->save($role);
return $user;
}
Source: https://laracasts.com/discuss/channels/laravel/attach-role-to-a-user-upon-registration?page=1

You don't currently have a roles() relation in your user model. Add the following
public function roles()
{
return $this->hasMany('App\Role');
}

Related

Issue: Argument #1 ($user) must be of type Illuminate\Contracts\Auth\Authenticatable, null given, called in

I'm beginner in Laravel. I'm using jetstream for auth. When I trying register to database, it saves to database but gives this error. So how can I fix this problem
My HomeController is:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
class HomeController extends Controller
{
protected $user;
public function __construct(){
$this->middleware(function ($request, $next) {
$this->user= Auth::user();
return $next($request);
});
}
public function main(){
return view('welcome');
}
public function home(){
return view('design2.index');
}
public function logout(Request $request) {
Auth::logout();
return redirect('/');
}
public function register(){
return view('design2.registerpage');
}
public function login_page(){
return view('design2.loginpage');
}
public function profile(){
return view('profile');
}
}
My user model is:
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Laravel\Jetstream\HasProfilePhoto;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens;
use HasFactory;
use HasProfilePhoto;
use Notifiable;
use TwoFactorAuthenticatable;
/**
* 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',
'two_factor_recovery_codes',
'two_factor_secret',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* The accessors to append to the model's array form.
*
* #var array
*/
protected $appends = [
'profile_photo_url',
];
}
My CreateNewUser is:
<?php
namespace App\Actions\Fortify;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Laravel\Fortify\Contracts\CreatesNewUsers;
use Laravel\Jetstream\Jetstream;
class CreateNewUser implements CreatesNewUsers
{
use PasswordValidationRules;
/**
* Validate and create a newly registered user.
*
* #param array $input
* #return \App\Models\User
*/
public function create(array $input)
{
Validator::make($input, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => $this->passwordRules(),
])->validate();
$save = User::create([
'name' => $input['name'],
'email' => $input['email'],
'password' => Hash::make($input['password']),
]);
}
}
Error is:
Illuminate\Auth\SessionGuard::login(): Argument #1 ($user) must be of type Illuminate\Contracts\Auth\Authenticatable, null given, called in /Applications/XAMPP/xamppfiles/htdocs/muzik/vendor/laravel/fortify/src/Http/Controllers/RegisteredUserController.php on line 56
Try to return created user instead of just save it in variable $save.
public function create(array $input)
{
Validator::make($input, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => $this->passwordRules(),
])->validate();
return User::create([
'name' => $input['name'],
'email' => $input['email'],
'password' => Hash::make($input['password']),
]);
}

Laravel Email Verification link not working?

I have set up an email verification to my Laravel APP, however when I register as a user and go to mailtrap.io and when I click on "Verify Email Address" button I get 403 This action is unauthorized, HOWEVER if I click on resend verification mail and then click on the button it works fine.
Here are my web routes:
Auth::routes(['verify' => true]);
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/', 'HomeController#index')->name('home');
Route::resource('challenge', 'ChallengesController');
Route::post('/challenge/join/{id}', 'ChallengesController#joinChallenge')->name('challenge.join');
Route::delete('/challenge/finish/{id}', 'ChallengesController#finishChallenge')->name('challenge.finish');
In my User model, I have implemented MustVerifyEmail
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'user_id', 'name', 'username', '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',
];
protected $primaryKey = 'user_id';
protected $keyType = 'string';
}
UPDATE
Here is my HomeController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware(['verified', 'auth']);
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
$user_id = auth()->id();
$user = User::find($user_id);
return view('home')
->with('challenges', $user->challenges)
->with('userChallenges', $user->userChallenges);
}
}
RegisterController:
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'username' => ['required', 'string', 'max:45', 'unique:users'],
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return User::create([
'user_id' => uniqid(),
'username' => $data['username'],
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
Make sure you don't have your authentication paths inside the auth middleware
Auth::routes(['verify' => true]);
Route::group(['middleware' => 'auth'], function () {
});

Getting User::create() not found in Laravel 5.5

When I try to register a user, I am getting an error:
Call to undefined method App\Models\User::create()
here is my User model:
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'first_name', 'last_name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
protected $table = 'users';
}
I have used the User model that is shipped with Laravel 5.5, but just moved it to the Models folder. I updated the config/auth file to point to App\Models\User. I have ran php artisan optimize and composer dump-autoload several times, to no avail.
Here is my Register Controller:
<?php
namespace App\Http\Controllers\Auth;
use App\Models\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller {
public $titles = [];
public $title = 'Registration';
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
public function showRegistrationForm() {
return view('auth.register')
->with('env', $this->env)
->with('titles', $this->titles)
->with('title', $this->title);
}
}
When extending Laravel User model from the Auth package, you should extend the User class from that package. The abstract class from package extends the Model and then you will have access to all model methods.
From Illuminate\Foundation\Auth\User:
class User extends Model implements
AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
}

FatalThrowableError:Argument 1 passed ..::fromUser() laravel 5.6

I use postman to add user or to login , user has added with sucess but I get this error
"Argument 1 passed to Tymon\JWTAuth\JWT::fromUser() must be an
instance of Tymon\JWTAuth\Contracts\JWTSubject, instance of App\User
given, called in C:\Users\Web
WorkStation\Desktop\laravelapp\jwtlaravel\vendor\tymon\jwt-auth\src\JWTAuth.php
on line 54"
and I found in this ligne this founction
public function attempt(array $credentials)
{
if (! $this->auth->byCredentials($credentials)) {
return false;
}
return $this->fromUser($this->user());
}
and this my user model :
<?php
namespace App;
use Tymon\JWTAuth\Contracts\JWTSubject;
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','username','lastname','tel','tel',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* #return array
*/
public function getJWTCustomClaims()
{
return [];
}
}
and this my register controller
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\User;
use JWTFactory;
use JWTAuth;
use Validator;
use Response;
class APIRegisterController extends Controller
{
//
public function register( Request $request){
$validator = Validator::make($request -> all(),[
'email' => 'required|string|email|max:255|unique:users',
'username' =>'required',
'tel' => 'required',
'name' => 'required',
'lastname' => 'required',
'adress' => 'required',
'password'=> 'required'
]);
if ($validator -> fails()) {
# code...
return response()->json($validator->errors());
}
User::create([
'name' => $request->get('name'),
'email' => $request->get('email'),
'tel' => $request->get('tel'),
'username' => $request->get('username'),
'lastname' => $request->get('lastname'),
'adress' => $request->get('adress'),
'password'=> bcrypt($request->get('password'))
]);
$user = User::first();
$token = JWTAuth::fromUser($user);
return Response::json( compact('token'));
}
}
Implement the JWTSubject in your User model:
class User extends Authenticatable implements JWTSubject
This requires that the User Model implements this contract in your model:
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Model implements JWTSubject {
Or
you have to update your User model to implement the Tymon\JWTAuth\Contracts\JWTSubject interface:
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Model implements JWTSubject{
/**
* Get the identifier that will be stored in the subject claim of the JWT.
*
* #return mixed
*/
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* #return array
*/
public function getJWTCustomClaims()
{
return [];
}
}

Laravel registration: Insert two rows into separated tables

I have a problem with inserting rows in Laravel.
Theory: I use simple Laravel authentication and have two tables.
users: id, name, password.
user_details: id, userID, email
After the registration it would be useful to insert rows into both tables, and the userID = id (in users table).
RegisterController.php
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
//$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'e_r' => $data['e_r'],
]);
$details = UserDetails::create([
'firstname' => 'joco',
'lastname' => 'nagy',
'email' =>$data['email'],
'position' => 'cleaner',
'salary' => '250000',
'amount_holiday' => '40'
]);
return $user;
}
}
(I have just tried to insert fake datas. There are default values in migration files.)
Models:
User.php
<?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', 'e_r',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function user_detail(){
return $this->hasOne("App\UserDetails");
}
}
Error:
FatalThrowableError in RegisterController.php line 74: Class
'App\Http\Controllers\Auth\UserDetails' not found
I do not understand why should be my model in Auth directory.
Have you include your model UserDetails?
Include it on top:
use App\User;
use App\UserDetails;
or
Change UserDetails to App\UserDetails.
$details = App\UserDetails::create([
'firstname' => 'joco',
'lastname' => 'nagy',
'email' =>$data['email'],
'position' => 'cleaner',
'salary' => '250000',
'amount_holiday' => '40'
]);
You should use use statement eg. use Your\Name\Space\UserDetails;
Without this declaration PHP is looking for UserDetails class in your current namespace, in your case App\Http\Controllers\Auth. That's why you get
'App\Http\Controllers\Auth\UserDetails' not found

Categories