Method Illuminate\Database\Query\Builder::profilesInfoModel does not exist. // RegisterController.php - laravel

what i need is to save some data besides creating the user, here is what I've been trying to do in my RegisterController.php :
protected function create(array $data)
{
if (isset($data['checkbox'])) {
$type = 1;
$available = 1;
} else {
$type = 0;
$available = 0;
}
$user = User::create([
'name' => $data['name'],
'username' => $data['username'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'type' => $type,
'available' => $available,
'company' => $data['company'],
'job' => $data['job'],
]);
$user->profilesInfoModel()->create([
'bio' => $data['bio'],
'site' => $data['site'],
'location' => $data['location'],
'education' => $data['education'],
]);
return $user->with('profilesInfoModel');
}
The User.php (Model) has a one to one relationship with profilesInfoModel (yes, i know i should change the name of the model to make it more comfortable).
But after trying to register a user... i get this error message: Method Illuminate\Database\Query\Builder::profilesInfoModel does not exist.
What is actually going on?

The relationship should be like this
User Model
public function profile()
{
return $this->hasOne(ProfileInfo::class, 'user_id');
}
Assuming you have ProfileInfo as Profile model and it has user_id as foreign key references users table id field
Now you can create profile from $user like this
$user->profile()->create([
'bio' => $data['bio'],
'site' => $data['site'],
'location' => $data['location'],
'education' => $data['education'],
]);
$user->load('profile'); //lazy eager load
return $user;

1.in App\Model\User
public function profilesInfoModel()
{
return $this->hasOne(App\Model\User);
}
2.to call
use App\Model\User
in RegisterController

Related

Laravel Auth::attempt() fails

When I register a new user and I want to sign him in by using auth attempt it doesn't work while the user is saved to database
static function register()
{
if(self::$validate['message'])
{
$user = User::create([
'name' => self::$values['name'],
'email' => self::$values['email'],
'password' => Hash::make(self::$values['password'])
]);
Auth::attempt($user,true);
Auth::attempt($user->only(['email','password']));
return result::repsonse(true);
} else
return self::$validate;
}
You can use Auth::login() method
static function register()
{
if(self::$validate['message'])
{
$user = User::create([
'name' => self::$values['name'],
'email' => self::$values['email'],
'password' => Hash::make(self::$values['password'])
]);
Auth::login($user);
return result::repsonse(true);
} else
return self::$validate;
}

Laravel 6 Factory, can't access relationship methods after using state

Suppose I have a user factory to create user, for specific user I want to add more information, for this I've defined state inside factory, but if I use state, then I can not call related method of user after user creation suppose I should assign role to the user using assignRole($role).
Following is my UserFactory.php
$factory->define(User::class, function (Faker $faker) {
return [
'email' => $faker->unique()->safeEmail,
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
'first_name' => $faker->name,
'last_name' => $faker->lastName,
'phone' => $faker->phoneNumber,
'password' => bcrypt('12345678'),
];
});
$factory->state(User::class, 'Admin', function (Faker $faker) {
$country = factory(Country::class)->create();
$province = factory(Province::class)->create();
static $afghanistanId = 1;
$admin= [
'about' => $faker->sentence($nbWords = 20, $variableNbWords = true),
'address' => $faker->address,
];
if($country->id == $afghanistanId) {
$admin['province_id'] = $province->id;
} else {
$admin['city'] = $faker->city;
}
return $admin;
});
Now if I use this factory like bellow:
$user = factory(User::class, $count)->state('Admin')->create();
$user->assignRole('Admin');
Following shows this error:
BadMethodCallException: Method Illuminate\Database\Eloquent\Collection::assignRole does not exist
By passing $count to the factory method $user = factory(User::class, $count)...->create(); you're creating multiple users and the return is a Collection like your Error says.
To assigne the 'Admin' role to each user you have to iterate them
$users = factory(User::class, $count)->state('Admin')->create();
foreach($users as $user)
$user->assignRole('Admin');

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 auth register insert data into two tables

i have my default registration for auth controller. i want to register also the emp_id created from users table to employee table. once registered.
my RegisterController
use App\User;
use App\Employee
public function count_users(){
$count = User::count();
return date('y').'-'.sprintf('%04d',$count);
}
protected function create(array $data)
{
return User::create([
'emp_id' => $this->count_users(),
'username' => $data['username'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
return Employee::create([
'emp_id' => $this->count_users()
]);
}
Please check following line in your code:
return User::create([ .....
Above line creates the user and returns the created user. Any code below "return" is not being called.
Please try following code:
use App\User;
use App\Employee
public function count_users(){
$count = User::count();
return date('y').'-'.sprintf('%04d',$count);
}
protected function create(array $data)
{
$emp_id = $this->count_users();
$user = User::create([
'emp_id' => $emp_id,
'username' => $data['username'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
Employee::create([
'emp_id' => $emp_id
]);
return $user;
}

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