Reputation: 402
I have a fresh Laravel install, with default web authentication and email verifications installed (which uses the default packages and install with artisan). This makes my User model extend Authentication and MustVerifyEmail, like so:
class User extends Authenticatable implements MustVerifyEmail {...}
Since this is a model, I would like to implement relationships with other models like a Post can have many comments. I cannot make use of the Model class because I can't extend two classes. So what the solution/alternative to this problem?
Upvotes: 0
Views: 2224
Reputation: 402
For anyone looking to use Laravel authentication with email verification and also wanting to extend User class with Model, then they will come across this situation where the class will already look something like this:
class User extends Authenticatable implements MustVerifyEmail {...}
To use Model relationships in Laravel you need to extend User with Model, like so:
class User extends Model
{
//
}
This comes as a problem, where PHP only allows a class to extend from one other class. So we can either extend from Authenticatable or Model
@matticustard already mentioned that "Authenticatable already extends Model". Hence, we can just extend Model and that would simply work.
If you have MustVerifyEmail implemented, then doing the above changes will give an error for not declaring the following methods: 'hasVerifiedEmail', 'markEmailAsVerified', 'sendEmailVerificationNotification' and 'getEmailForVerification'.
For this issue, simply define the methods like so:
/**
* Determine if the user has verified their email address.
*
* @return bool
*/
public function hasVerifiedEmail()
{
return ! is_null($this->email_verified_at);
}
/**
* Mark the given user's email as verified.
*
* @return bool
*/
public function markEmailAsVerified()
{
return $this->forceFill([
'email_verified_at' => $this->freshTimestamp(),
])->save();
}
/**
* Send the email verification notification.
*
* @return void
*/
public function sendEmailVerificationNotification()
{
$this->notify(new Notifications\VerifyEmail);
}
/**
* Get the email address that should be used for verification.
*
* @return string
*/
public function getEmailForVerification()
{
return $this->email;
}
NOTE: The above code is simply from the trait defined in Illuminate\Auth\MustVerifyEmail;
This is a solution that worked for me and if you have any suggestions or another solution, feel free to answer/comment below.
Upvotes: 1