Laravel assign User ID when registering - laravel

I was creating a new User when Registering with Laravel PHP, this way:
User::create([
'name' => $data['name'],
'surname' => $data['surname'],
'pass' => encrypt('password')
])
It works perfect, but now I want to create an empty Business and assign it to him, like:
Business::create([
'name' => 'Change the name of your Business',
'address' => 'Introduce your address here',
'owner_id' => ?? // here would go this new user's ID
])
How can I assign the ID that this new user will have? He's not registered yet at this point to assing to it owner_id = Auth::user()->id. So how can I make it??
Thanks a lot!

The create method will return the created model instance, so you can save it like this:
$user = User::create([
'name' => $data['name'],
'surname' => $data['surname'],
'pass' => encrypt('password')
]);
and then:
Business::create([
'name' => 'Change the name of your Business',
'address' => 'Introduce your address here',
'owner_id' => $user->id
]);

Related

How to store data in one table with distinct attributes in Laravel 8

Need a little help with Laravel 8, I have two users with the same attributes but the other one has another attribute :
Seeker: name, email, password
Agent: name, email, password, broker license no
This is my form:
If the user registers as an agent, other fields require only for an agent.
I'm having trouble on how to store it in a database.
protected function create(array $data)
{
$r_id = isset($data['agent']) ? 2 : 3;
return User::create([
'given_name' => $data['given_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'role_id' => $r_id, ]);
}
you can create another table for information agents and use relationship with column id in table users
Sample code :
$user = User::create([
'given_name' => $data['given_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'role_id' => $r_id
]);
if($r_id === 2){
Agent::create([
'user_id' => $user->id,
.
.
...
]);
}
User relation to Agent :
public function agent()
{
return $this->belongsTo(Agent::class, 'id', 'user_id');
}

How is it possible to retrieve the id of a Model right after it was created in the same controller function?

Let me show you my code, and place comments for you guys to better understand:
$homework = new Homework([ // I create Homework (And I indeed want to get the ID of the one that was just created).
'subject_id' => $request->subject_id,
'user_id' => auth()->user()->id,
'title' => $request->name,
'image' => $path,
'progress' => $request->progress,
'description' => $request->description,
'duedate' => $request->date
]);
$homework->save(); // I save it
$homeworkid = Homework::where('id', $id)->first(); // I try to retrieve it, but I'm not sure how to get it as I need to define `$id`.
$progress = newProgress([
'user_id' => auth()->user()->id,
'homework_id' => $homeworkid, // I need this for the relationship to work.
'title' => 'Initial Progress',
'description' => 'This progress is auto-generated when you create an assignment',
'username' => auth()->user()->name,
'progress' => $homeworkid->progress
]);
$progress->save(); // I save the progress
Well, as you saw, I'm trying to retrieve the ID of Homework right after it was created, but I'm not sure how to define $id in order to get it.
There is no need to instantiate a new model and saving it if your are not doing anything between instantiating and saving, you can use the create method instead:
$homework = Homework::create([
'subject_id' => $request->subject_id,
'user_id' => auth()->user()->id,
'title' => $request->name,
'image' => $path,
'progress' => $request->progress,
'description' => $request->description,
'duedate' => $request->date
]);
$homework->id; // get the id
After saving / creating the model you can access the id like you normally would:
$homework->id
What you then could do is setup the relationships between your models so you can do the following after creating a new homework:
$homework->newProgress()->create([
'user_id' => auth()->user()->id,
'title' => 'Initial Progress',
'description' => 'This progress is auto-generated when you create an assignment',
'username' => auth()->user()->name,
'progress' => $homework->progress
]);
This way you don't have to pass the homework id when creating a new newProgress, laravel will pass it automatically for you.
This is very simple for you. No need to complex it.
$homework->save(); // I save it
After this line just use only
$progress = newProgress([
'user_id' => auth()->user()->id,
'homework_id' => $homework->id, // I need this for the relationship to work.
'title' => 'Initial Progress',
'description' => 'This progress is auto-generated when you create an assignment',
'username' => auth()->user()->name,
'progress' => $homework->progress
]);
You don't no need this line of code
$homeworkid = Homework::where('id', $id)->first(); // I try to retrieve it, but I'm not sure how to get it as I need to define `$id`.
$data = $homework->save();
Get the ID this way: $data->id

How to Validate Record in Update Case in the Following Critical Situation using Laravel?

I want to update record but before update i want to check :-
1. if user exists at time not allowed to update.
Example :-
User jay try to update his name, but user insert same name which is already exists in jay field. at time i want to allow user to update but this code give error that username already exists. What i should do ??
Controller :-
public function update_data($update_id){
$gender_list = ['Male', 'Female', 'Other'];
$country_list = ['India', 'US', 'UK', 'Germany', 'Austraila'];
$Validator = $this->validate(request(), [
'username' => 'required|unique:userlists|alpha_num|max:30',
'email' => ['required', 'unique:userlists', 'email', 'regex:/((yahoo|gmail|hotmail)\.com)/'],
'password' => 'required',
'bod' => 'required|after_or_equal:today',
'comments' => 'required',
'phone_no' => 'required|numeric',
'country' => 'required|alpha',
'gender' => 'required',
'agreement' => 'required',
],[
'required' => 'Please Enter Your :attribute',
]);
if(!in_array($request->gender, $gender_list) || !in_array($request->country, $country_list)){
session()->flash('G_msg', 'Hello Hackes Please Go Back');
return back();
}
if($Validator->passes()){
// updation code.
}
}
You can use validation like below:
'username' => ['required','alpha_num', 'max:30',Rule::unique('userlists')->ignore($update_id)]
Make sure Rule is defined above Class:
use Illuminate\Validation\Rule;
try unique
'username' => 'required|unique:table_name,username,' . $update_id . ',user_id',
You may use Rule
use Illuminate\Validation\Rule;
'username' => ['required','alpha_num', 'max:30',Rule::unique('userlists')->ignore($update_id)]

How to access the reset password mailable in the new version of laravel

I would like to use the reset password mailable for my project but I do not know how to access it in laravel 6.1
Here is my method
public function store(Request $request)
{
$validatedData = $request->validate([
'address_id' => 'required',
'name'=> 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'POBox' =>['required', 'min:6', 'max:6'],
'role_id' => 'required',
]);
$quickpass = substr( str_shuffle( str_repeat( 'abcdefghijklmnopqrstuvwxyz0123456789', 10 ) ), 0, 10 );
$newuser = User::create([
'address_id' =>$request->address_id,
'name'=> $request->name,
'email' => $request->email,
'POBox'=> $request->POBox,
'password' => Hash::make($quickpass),
'role_id' => $request->role_id,
]);
Mail::to($newuser->email)
->send( );
return view('admin.index')->with('message','The user has been created and a password reset email has been sent to them.');
}
The Notification used is Illuminate\Auth\Notifications\ResetPassword. It builds a MailMessage inline.
The PasswordBroker can be used to create the token and send off the notification for you. The method sendResetLink will take an array of credentials to find the User by.
Illuminate\Auth\Passwords\PasswordBroker
$resp = Illuminate\Support\Facades\Password::broker()->sendResetLink([
'email' => '...',
]);

FirstOrCreate with only some attributes

I want to create a user if not matched:
$newUser=User::firstOrCreate(array('name' => $user->name, 'email' => $user->email,'avatar'=>$user->avatar));
But, i also need to store token which will be different every time even if other attributes matches. So, i need something like match with only name, email, avatar but also store or update token.
You can do it in this way:
$newUser = User::firstOrCreate([
'name' => $user->name,
'email' => $user->email,
'avatar' => $user->avatar
]);
$newUser->token = bin2hex(openssl_random_pseudo_bytes(16));
$newUser->save();
Hope this helps!
Pass an array of additional values as second parameter:
$newUser = User::firstOrCreate(
['name' => $user->name, 'email' => $user->email, 'avatar' => $user->avatar],
['token' => $token]
);
To understand how it works look at source code of firstOrCreate() method.

Resources