How to add data to related table in Auth Laravel? - laravel

I use the standard mechanism authentication in Laravel 5.3 is built by command:php artisan make:auth.
So, It have created controller RegisterController with the following methods:
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]));
}
So, I need to extend this method that to add data to related table for User table. For this I do:
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
])->roles()->attach(Role::where('name', "admin"))->first());
}
After this I get error:
FatalThrowableError in SessionGuard.php line 441:
Type error: Argument 1 passed to Illuminate\Auth\SessionGuard::login() must implement interface Illuminate\Contracts\Auth\Authenticatable, null given, called in \vendor\laravel\framework\src\Illuminate\Foundation\Auth\RegistersUsers.php on line 32

I didn't use Laravel's auth logic, but it looks like the user gets logged in right after they're created. To log the user in Laravel needs the User object, hence:
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
The create() method returns Model. You, however, added attach() to the return statement, and if you take a look at the API, the method returns void which eventually translates to null mentioned in the error message.
What you want to do, is something like this:
protected function create(array $data) {
// Create the User and store the object
$newUser = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
// Add extra data
$adminRole = Role::where('name', 'like', 'admin')->first();
$newUser->roles()->attach($adminRole->id);
// Return the new User object
return $newUser;
}
Note: I assumed you have an id column in your role(s) table.

Related

Laravel: send email on registration

I want to be able to send emails through the registration of my system. I have set up all the mailtrap information and included all my key imports. However im not sure if the actual way of sending the email is correct. I keep getting error: undefined variable email, see the code below:
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
Mail::to($data['email'])->send(new WelcomeMail());
}
}
I have imported welcomemail and the facades import so everything is good to go, however i am unable to send the email as of now.
Any code after return will not execute. Do all your logic and then return.
$user = User::create([...])
Mail::to($user)->send(new WelcomeMail());
return $user;
I also did:
Mail::to($data['email'])->send(new WelcomeMail());
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
and this worked perfectly fine

I have added avatar column to the generated users table, how to make default value to the avatar column

I am using Laravel Framework, I have generated all Register and Login through "$php artisan make:auth" command, now I have added a new column called "avatar" in the users table, and I want to set it to "noimage.jpg", so each time I register by default "noimage.jpg" will be added.
RegisterController
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'username' => $data['username'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'avatar' => 'noimage.jpg' //How it suppose to be?
]);
}
You also have to add avatar to the $fillable property of your model. Otherwise you cannot assign it with create. See docs on Mass Assignment.
Instead you could manually assign the avatar:
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'username' => $data['username'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$user->avatar = 'noimage.jpg';
return $user;
}
Another way to set a default value for your model is to use Laravel lifecycle:
const DEFAULT_AVATAR = 'noimage.jpg'
protected static function boot()
{
parent::boot();
static::creating(function (User $user) {
if (!$user->avatar) {
$user->avatar = self::DEFAULT_AVATAR;
}
});
}
See: https://laravel.com/docs/5.8/eloquent#events

Laravel 5 not generating api token on register

I have added a column for api_token and in my register controller , while creating the user I am trying to generate a unique id , but its not generating any code . Here is my create user function in register controller
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'api_token' => md5($data['email'].$data['name']),
'password' => bcrypt($data['password']),
]);
}
Do I need to add this somewhere else?
As cbaconnier mentioned, you also need to add api_token to your $fillable array in the User model.

how to create new user only if there is data in database-Laravel

I have done programming with other frameworks but this is new to me, thanks for your time in advanced, I'm trying to create new user on a condition that if there is data in another table then new user is created otherwise not I have put my code inside if else statement and is throwing errors.
my function for creating new user is listed below:
protected function create(array $data)
{
/*$exists = \DB::table('received_pay')->where('email', $data['email'])->first(); */
$exists=\DB::table('received_pay')->where('email', '=', $data['email'])->where('token', $data['token'])->exists();
if ($exists === null) {
// user doesn't exist
return User::create([
'username' => $data['username'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'token' => $data['token'],
]);
}else{
return null;
}
}
}
this is the error it throws
You need to return User instance from the RegisterController#create method by default, you can't return null. So, do this instead of return null;:
return User::where('email', $data['email'])->first();
If it's an option to check if the user exists in the users table, you can use the firstOrCreate method:
protected function create(array $data)
{
return User::firstOrCreate(['email' => $data['email'], [
'username' => $data['username'],
'password' => bcrypt($data['password']),
'token' => $data['token'],
]);
}
Also, you if want to check if a user exists in the received_pay table, you can leave original RegisterController#create method and add this rule to the RegisterController#validator method:
'email' => 'unique:received_pay,email',
This will not allow Laravel to create a new user if a user with the same email already exists in the received_pay table.

Laravel Email Confirmation On Registration

I need to send an email after a new user is created.
But I don't know how to return to the home page without getting an error.
This is what I am doing right now.
User::create([
'name' => $data['name'],
'username' => $data['username'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'phone' => bcrypt($data['phone']),
'confirmation_code' => str_random(30),
]);
Email_function();
if (Auth::attempt(['email' => $data['email'], 'password' => bcrypt($data['password']) ])) {
// Authentication passed...
return redirect('/');
}
I keep getting this as my error message.
SErrorException in SessionGuard.php line 439:
Argument 1 passed to Illuminate\Auth\SessionGuard::login() must implement interface Illuminate\Contracts\Auth\Authenticatable, null given, called in /Applications/XAMPP/xamppfiles/htdocs/sniddl/vendor/laravel/framework/src/Illuminate/Foundation/Auth/RegistersUsers.php on line 63 and defined
Edit:
changed the title to reflect the answer.
Here is a modified create function with an added email function for your register controller
Make sure Request is included in the pages top with namespaces being used:
use Illuminate\Http\Request;
Change the create function in your controller:
protected function create(Request $data)
{
$user = new User;
$user->name = $data->input('name');
$user->username = $data->input('username');
$user->email = $data->input('email');
$user->password = bcrypt($data->input('password'));
$user->phone = bcrypt($data->input('phone'));
$user->confirmation_code = str_random(60);
$user->save();
if ($user->save()) {
$this->sendEmail($user);
return redirect('VIEWPATH.VIEWFILE')->with('status', 'Successfully created user.');
} else {
return redirect('VIEWPATH.VIEWFILE')->with('status', 'User not created.');
}
}
Create the sendEmail function in the same controller that will use Laravels built in email. Make sure you create and your HTML email:
public function sendEmail(User $user)
{
$data = array(
'name' => $user->name,
'code' => $user->confirmation_code,
);
\Mail::queue('EMAILVIEWPATH.HTMLEMAILVIEWFILE', $data, function($message) use ($user) {
$message->subject( 'Subject line Here' );
$message->to($user->email);
});
}
NOTE:
Your going to need to update the VIEWPATH.VIEWFILE and EMAILVIEWPATH.HTMLEMAILVIEWFILE at a minimium in the examples above.
Check the repos below for CONTROLLER :
https://github.com/laravel/laravel/blob/master/app/Http/Controllers/Auth/RegisterController.php
https://github.com/jeremykenedy/laravel-auth/blob/master/app/Http/Controllers/Auth/AuthController.php
REGISTER VIEW(blade) EXAMPLE
https://github.com/jeremykenedy/laravel-auth/blob/master/resources/views/auth/register.blade.php
EMAIL VIEW THAT RECEIVES VARIABLES:
https://github.com/jeremykenedy/laravel-auth/blob/master/resources/views/emails/activateAccount.blade.php
Ok so it turns out, by setting User::create as a variable it allows you to login in the user by returning the variable. Like this.
$user = User::create([
'name' => $data['name'],
'username' => $data['username'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'phone' => bcrypt($data['phone']),
'confirmation_code' => str_random(30),
]);
Email_function();
return $user;

Resources