Call to a member function details() on null when assign model? - laravel

Use model is:
public function details()
{
return $this->hasOne(UserDetails::class, 'user_id', 'id');
}
First I create user model:
$user = User::create([
'email' => $request->inn,
'password' => Hash::make($request->password),
]);
Then I tried to assign details of users:
$user->details()->create($user_details);
It returns me this error:
Call to a member function details() on null

You have not provided a lot of information with this issue however I would suggest that the issue is that the User is not being created because your attributes on the User model are guarded.
Make sure you have one of the following solutions on the your User model
protected $fillable = [
'email',
'password'
]
Or
protected $guarded = []
Failing to add these means that Laravel will not allow you to add details to the model using anything other than save() method

Two solutions for this.
Create method
If you are using create method it's not creating object as you're doing right now.
$userid = User::create([
'email' => $request->inn,
'password' => Hash::make($request->password),
])->id;
User::find($userid)->details()->create($user_details);
In your question $user is not getting object that's why this error you are getting.
Object Method
$user = new User;
$user->email = $request->inn;
$user->password= Hash::make($request->password);
$user->save();
//here $user is an instance of User so if you dd($user) you'll get an object.
$user->details()->create($user_details);
Hope this will work for you.

Related

Laravel Type Error:Argument 1 passed to Illuminate\Database\Eloquent\Relations\BelongsToMany::save() must be an instance

Full Error:
TypeError
Argument 1 passed to Illuminate\Database\Eloquent\Relations\BelongsToMany::save() must be an instance of Illuminate\Database\Eloquent\Model, null given, called in F:\php\phpcourse\website\app\Http\Controllers\Auth\RegisterController.php on line 75
I am trying to assign a guest role to the user when the user registers the account, seeing attach role to a user upon registration laravel 5.4
But I faced this error. So I don't know how to solve this rid because I am beginner at Laravel.
Here is my code
User model
public function roles()
{
return $this->belongsToMany('App\Models\Role')->withPivot('role_id');
}
RegisterController
protected function create(array $data)
{
$role = \App\Models\Role::where('name', 'guest')->first();
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'is_active' => 1, // add new
]);
$user->roles()->save($role);
return $user;
}
I see no problem in the code, just confirm you have guest role in roles table
$role = \App\Models\Role::where('name', 'guest')->first();
first() can return null if no record found

Laravel 7: How to access a function in User model from API without signing in

I have a function in the user model used to send the API email verification message. It works fine in the registration function after User::create
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'phone' => $request->phone,
'password' => $request->password,
'sms_code' => $sms_code,
]);
$user->sendApiEmailVerificationNotification();
Now I'm trying to resend the verification email in another function
$user = DB::table('users')->where('email', $email)->first();
$user->sendApiEmailVerificationNotification();
User model:
public function sendApiEmailVerificationNotification()
{
$this->notify(new VerifyApiEmail);
}
But I get
"message": "Call to undefined method stdClass::sendApiEmailVerificationNotification()",
How to use this function using the $user object?
Instead of
$user = DB::table('users')->where('email', $email)->first();
$user->sendApiEmailVerificationNotification();
use this:
$user = User::where('email', $email)->first());
$user->sendApiEmailVerificationNotification();
why?
The User::where(..) returns an eloquent object whilst DB::table does not.
sendApiEmailVerificationNotification only exists on eloquent models extending authenticable.

Update two tables using one function in Laravel

I'm building an app using Laravel 5.7 and Vue.js2. I have two tables: departments and users. A user can be a chief of a department. I made the relationship between the models. I want it so that when I create a new department, the type of the chief will be changed on the user's table to 'chief.'
DepartmentController
public function store(Request $request)
{
$this->validate($request, [
'name' => 'string|required|max:191',
'bio' => 'string|required',
'user_id' => 'integer|required|unique:departements'
]);
return Department::create([
'name' => $request['name'],
'user_id' => $request['user_id'],
'bio' => $request['bio']
]);
}
Can you try this.
Controller
public function store(Request $request)
{
$this->validate($request,[
'name'=>'string|required|max:191',
'bio'=>'string|required',
'user_id'=>'integer|required|unique:departements'
]);
$new_department = Department::create([
'name'=>$request['name'],
'user_id'=>$request['user_id'],
'bio'=>$request['bio']
]);
$get_user = User::where('id', $request['user_id'])->first();
if($get_user)
{
$get_user->type = 'chief';
$get_user->save();
}
return ['message' => 'success'];
}
In this code, After saving the New Department I get the UserData in UserModel where id is the $request['user_id] then check it if exists.
If exists, I change the type to 'chief' and save.
If you have relationship between two models then you can update like this
$product = Department::with('relationship_function_name')->find($id);
$product->fields= $request->input_name;
$product->relationship_function_name->field_name = $request->input_name;
$product->update();
Hope this helps :)

$user->id is there but won't save to a table in RegisterController | Laravel

I'm having an issue with the Register Controller, when a user registers I want my Contacts table to create an entry for that user automatically. Everything works and when i do dd($user_id) I can see the id of the new user that just was made but it refuses to save it to the database. I am not sure why, the user_id has no problem in other instances like when a user makes a contact. Here is the Controller:
protected function create(array $data)
{
$user = new User([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
$user->save();
$user_id = $user->id;
Contact::create([
'user_id' => $user_id,
'fullName' => 'Me',
// dd($user_id),
]);
return $user;
}
}
Any help would be much appreciated.
The silliest thing, just figured it out after hours of trying to fix this. My Contact.php did not have user_id inside fillable!
protected $fillable = ['user_id', 'fullName', 'email', 'phoneNumber'];

Laravel User - Role many to many relationship

I have created a Role table which has a many to many relationship with the User table. Models and everything in place plus i can seed all tables correct to create a default user + 3 roles.
I want to modify the scaffolded register controller so i can attach a role along with the other attributes (name, mail etc). The default create method looks something like this:
protected function create(array $data)
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
how do i call Role model ? and how do i pass it in the create function and ultimately to the view ?
My initial thought was:
use App\Role;
at the beginning of the file and
$roles = Role::all();
maybe on the create function ? that is probably wrong but i cannot think something else.
Plus how do i call it after on the view ? Role table has 3 predefined roles as i mentioned above.
You need to create user first, then you need to attach roles and return user instance. This should work for you:
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
$roles = [2, 4];
$user->roles()->attach($roles);
return $user;
}

Resources