I am using Laravel 7 and I am trying to verify my email I have followed all the steps mentioned in the documentation but I am still getting this error please me to resolve this error, Thanks
I added the user model code here
<?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 = [
'first_name', 'last_name', 'email', 'password', 'permissions'
];
/**
* 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',
];
}
here is web.php
Auth::routes(['verify'=> true]);
Route::prefix('student')->middleware(['auth', 'verified'])->group(function () {
Route::get('dashboard', 'StudentController#dashboard');
});
The $request is sending a null value because you need to be logged in (authenticated) in order to get an instance of the $user
Make sure you have a middleware of auth on your route
Assigning Middleware To Routes:
Route::get('admin/profile', function () {
//
})->middleware('auth');
or Middleware Groups:
Route::group(['middleware' => ['auth']], function () {
Route::get('admin/profile', function(){
//your function here
});
});
Laravel Official Doc
only users logged could acheave the function hasVerifiedEmail() , because of that you get the response : Call to a member function hasVerifiedEmail() on null ,
to fix that issue you have to customise show function in VerificationController.php
public function show(Request $request)
{
//login user
if (auth()->user())
{
return $request->user()->hasVerifiedEmail()
? redirect($this->redirectPath())
: view('auth.verify');
}
//guest
else
{
return $request->user()
? redirect($this->redirectPath())
: redirect('/login');
}
}
Related
what im trying to do is fetcing role data from single actions controller and got error messege when i test it out from postman. "message": "Call to undefined method App\Models\User::auth()", for anyone can give me hint or solution to fix this problems will highly appriciate. for further information im using jwt for auth, api as the guard.
so let me show you my code.
Controller:
<?php
namespace App\Http\Controllers\Api\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
class RoleController extends Controller
{
public function __invoke()
{
return User::auth()->user()->getRoleNames();
}
}
Model:
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable implements JWTSubject
{
use HasFactory, Notifiable, HasRoles;
protected $guard_name = "api";
/**
* 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 getJWTIdentifier(){
return $this->getKey();
}
public function getJWTCustomClaims(){
return [];
}
}
routes:
//group route with prefix "admin"
Route::prefix('admin')->group(function () {
//route login
Route::post('/login', [App\Http\Controllers\Api\Admin\LoginController::class, 'index']);
//group route with middleware "auth"
Route::group(['middleware' => 'auth:api'], function() {
//data user
Route::get('/user', [App\Http\Controllers\Api\Admin\LoginController::class, 'getUser']);
//refresh token JWT
Route::get('/refresh', [App\Http\Controllers\Api\Admin\LoginController::class, 'refreshToken']);
//logout
Route::post('/logout', [App\Http\Controllers\Api\Admin\LoginController::class, 'logout']);
Route::prefix('authorization')->group(function () {
Route::get('/roles', RoleController::class);// not working
});
});
});
There are few ways you can try for getting those roles:
shows all the role names
Auth::user()->roles
$roles = $user->getRoleNames(); // Returns a collection
check user has specific role
Auth::user()->hasRole('admin')
check user has any roles
Auth::user()->hasAnyRole(['super_admin', 'vendor'])
For other usage take a look at the site:
Spatie roles and permission info
I am having an issue following a tutorial on YouTube about relationships.
I have replicated this code from the tutorial and I keep getting errors.
I've tried changing the controller code from auth() to app etc.
Also, I've tried re-running migrations:fresh etc and nothing.
User Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Cashier\Billable;
class User extends Authenticatable
{
use Notifiable, Billable;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* Get the Instance associated with the user.
*
* #return HasMany
*/
public function instance()
{
return $this->hasMany(Instance::class);
}
}
Instance Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Instance extends Model
{
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'name'
];
public function user()
{
return $this->belongsTo(User::class);
}
}
Controller
<?php
namespace App\Http\Controllers;
class SyncController extends Controller
{
public function successful()
{
return auth()->user()->instance()->create(['name' => 'test']);
}
}
Error
Call to a member function instance() on null {"exception":"[object] (Error(code: 0): Call to a member function instance() on null at /home/#/cc.#.io/app/Http/Controllers/SyncController.php:14)
[stacktrace]
Edit:
Route::middleware(['auth'])->group(function() {
Route::get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
Route::get('/subscribe', SyncController::class);
});
Check if your route is guarded by auth middleware. If not you can add that in order to fix. You might use Route group like following -
Route::group(['middleware' => ['auth']], function () {
Route::resource('your_url', 'YourController');
// Or whatever route you want to add...
});
This is because the auth()->user is getting null and it will be necessary to check if the value was actually received after the call was made.
I'm facing a strange problem with Laravel Relations.
I'd like to access an event with many users (works perfect).
<?php
$event_with_user = Event::with('registered_users')->where('id', 253)->get();
dd($event_with_user);
And I'd like to access a user with all connected events:
<?php
$user_with_event = User::with('registered_events')->where('id', 1)->get();
dd($user_with_event);
Where I always receive this error:
Illuminate\Database\Eloquent\RelationNotFoundException
"Call to undefined relationship [registered_events] on model [App\User]."
I've checked the relations multiple times, but can't find a mistake. Does anyone else had that issue?
My Models
User.php
<?php
namespace App;
use App\Event;
use App\UserType;
use App\EventUser;
use App\Department;
use App\Evaluation;
use App\UserLocation;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'fname', 'lname', 'email', 'password', 'phone', 'email_verified_at', 'admin', 'user_type_id', 'last_login_at', 'last_login_ip', 'user_location_id', 'user_notification_type_id', 'user_notification_setting_id', 'slack_user_id', 'joinpoints_user_id'
];
/**
* 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 registered_events()
{
return $this->belongsToMany(Event::class, 'event_user', 'event_id', 'user_id');
}
}
Event.php
<?php
namespace App;
use App\User;
use App\EventRoom;
use App\EventType;
use App\EventStatus;
use App\EventLocation;
use App\EventParticipant;
use App\EventParticipantItems;
use Illuminate\Database\Eloquent\Model;
use Cviebrock\EloquentSluggable\Sluggable;
class Event extends Model
{
use Sluggable;
protected $fillable = [
'event_type_id', 'user_id', 'status', 'customer', 'slug', 'datetime', 'duration','embed_chat','number_of_participants','heading', 'description_1', 'description_2', 'livestream_link', 'logo_link', 'event_password', 'participants_per_room', 'youtube_id', 'embed_code', 'session_link', 'hide_breakout', 'help_link', 'lang', 'layout', 'btn2_text', 'btn2_link', 'help_text', 'background_url', 'black_font',
];
protected $dates = ['datetime'];
public function getRouteKeyName()
{
return 'slug';
}
/**
* Return the sluggable configuration array for this model.
*
* #return array
*/
public function sluggable()
{
return [
'slug' => [
'source' => 'customer'
]
];
}
public function registered_users()
{
return $this->belongsToMany(User::class, 'event_user', 'user_id', 'event_id')->withPivot('id', 'user_status', 'eventmanager', 'created_at', 'updated_at');
}
}
My Tables:
user: id,....
event: id,...
event_user: id, user_id, event_id,...
Look a bit closer at your models :
return $this->belongsToMany(Event::class, 'event_user', 'event_id', 'user_id');
and
return $this->belongsToMany(User::class, 'event_user', 'event_id', 'user_id');
Whilst the table is right, you will need to swap the order of event_id and user_id on one of them...
Looks like you swapped the (foreign) keys:
In User.php:
public function registered_events()
{
return $this->belongsToMany(Event::class, 'event_user', 'user_id', 'event_id');
}
In Event.php:
public function registered_users()
{
return $this->belongsToMany(User::class, 'event_user', 'event_id', 'user_id')->withPivot('id', 'user_status', 'eventmanager', 'created_at', 'updated_at');
}
As you follow the correct Laravel database structure, you could simply put
return $this->belongsToMany(Event::class); in User.php and
return $this->belongsToMany(User::class)->withPivot(...); in Event.php
I've been searching everywhere for a solution to my issue. I've created a welcome email, created the Mailable, Controller, and View. But for some reason, the $user isn't showing in the email itself. It's blank. Am I missing something?
Mailable
<?php
namespace App\Http\Mail;
use App\User;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class Welcome extends Mailable
{
use Queueable, SerializesModels;
public $user;
/**
* #return void
*/
public function _construct(User $user)
{
$this->user = $user;
}
/**
*#return $this
*/
public function build()
{
return $this->view('emails.welcome')->subject('Welcome to');
}
}
Controller
<?php
namespace App\Http\Controllers\Auth;
use Mail;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Auth;
use App\Http\Mail\Welcome;
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 = '/dashboard';
/**
* 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|max:255',
'last_name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'mobile' => 'required',
'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([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'mobile' => $data['mobile'],
'password' => bcrypt($data['password']),
'payment_mode' => 'CASH',
]);
Mail::to($data['email'])->send(new Welcome($user));
return $user;
// send welcome email here
}
/**
* Show the application registration form.
*
* #return \Illuminate\Http\Response
*/
public function showRegistrationForm()
{
return view('user.auth.register');
}
}
View (shortened to show problem)
Welcome {{ $user->first_name }}
User
<?php
namespace App;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use HasApiTokens,Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'first_name', 'last_name', 'email', 'mobile', 'picture', 'password', 'device_type','device_token','login_by', 'payment_mode','social_unique_id','device_id','wallet_balance'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token', 'created_at', 'updated_at'
];
}
As was mentioned, everything passes successfully, however, in the email itself, the name of the user is blank. Please help!
I got it working for anyone else dealing with same issue. I changed the register controller and just skipped the mailable entirely. In other words, I didn't need a separate mailable. Below is the result.
Mail::send('emails.welcome', [
'first_name' => $data['first_name'],
'email' => $data['email']
], function ($mail) use($data) {
$mail->from('Whatever', 'site/company name');
$mail->to($data['email'])->subject('Whatever');
});
return $user;
And in the view I just pass the first name like so
Welcome {{ $first_name }}
I am using Laravel 5.3 and I want to send verification mail using the following
php artisen make:auth
php artisen make:mail ConfirmationEmail
ConfirmationEmail.php
<?php
namespace App\Mail;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class ConfirmationEmail extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* #return void
*/
public $user;
public function __construct(User $user)
{
$this->user = $user;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->view('emails.confirmation');
}
}
emails/confirmation.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sign Up Confirmation</title>
</head>
<body>
<h1>Thanks for signing up!</h1>
<p>
We just need you to <a href='{{ url("register/confirm/{$user->token}") }}'>confirm your email address</a> real quick!
</p>
</body>
</html>
UserController.php
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email|unique:users',
'name' => 'required|string',
'password' => 'required|string|min:6',
'country' => 'required'
]);
if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()], 401);
}
$input = $request->all();
$input['password'] = bcrypt($input['password']);
$input['user_pin'] = $this->generatePIN();
$user = User::create($input);
Mail::to($user->email)->send(new ConfirmationEmail($user));
$success['token'] = $user->createToken('MyApp')->accessToken;
$success['user'] = $user ;
$now = Carbon::now();
UserLocation::create(['user_pin' => $input['user_pin'] , 'lat'=> 0.0 , 'lng' => 0.0 , 'located_at' => $now]);
return response()->json(['success'=>$success], $this->successStatus);
}
Models/User.php
<?php
vnamespace App\Models;
use App\User as BaseUser;
class User extends BaseUser
{
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function groups(){
return $this->belongsToMany(Group::class, 'group_member', 'member_id', 'group_id');
}
public function sentRequests(){
return $this->hasMany(Request::class, 'from_user_pin', 'user_pin');
}
public function receivedRequests(){
return $this->hasMany(Request::class, 'to_user_pin', 'user_pin');
}
public function locations(){
return $this->hasMany(UserLocation::class, 'user_pin', 'user_pin');
}
}
App\User.php
<?php
namespace App;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
protected $guarded = ['id'];
/**
* The attributes that are mass assignable.
*
* #var array
*/
/*protected $fillable = [
'name', 'email', 'password',
];*/
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
I am now getting this error
ErrorException in Model.php line 2709:
Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation (View: /var/www/html/group_map_v1/resources/views/emails/confirmation.blade.php)
token is a method on the model. When you try to access the dynamic property on the model, it looks for an attribute then for relationship method (or already loaded relationship) by that name.
You have no attribute named token. When you try to access it via the dynamic property it looks for a method named token (this is how it can access relationships via that property). When it does this it hits that method and that method does not return a relationship type object. So Eloquent breaks at that point as that property is for attributes and relationships, and it can't do anything with it.
asklagbox - blog - eloquent misunderstandings - dynamic properties and relationships
You're getting this error, you're trying to use a model method as a relationship, but this method doesn't return one. The relationship should look like this:
public function relationship()
{
return $this->hasMany(Model::class);
}
Update
HasApiTokens trait has a method named token() which is a simple accessor:
public function token()
{
return $this->accessToken;
}
When you do $user->token, Laravel sees this method and trying to use it as a relationship.
So, what you want to do is to rename your token property in the users table to something else.
Thanks to #lagbox for the pointing in the right direction.