FirstOrCreate with only some attributes - laravel

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.

Related

error getting a user existing in laravel sanctum

I have a error, I'm using sanctum and I want to check that the email does not exist
the if returns an empty array but the if is satisfied because it returns true
$mail = $request->input(['email']);
if ($search = User::where('email', $mail)->get()) {
return response()->json(['msg' => 'account already exist'], 409);
} else {
$validate = $request->validate([
'name' => 'required|string|',
'email' => 'required|string',
'password' => 'required|string'
]);
}
any solution?
Why not use the Laravel validation since this looks more like validation, so something like:
$request->validate([
'name' => 'required|string|',
'email' => 'required|string|email|unique:users,email',
'password' => 'required|string'
]);
with this you don't need to do an if else. You can check the Laravel docs on https://laravel.com/docs/8.x/validation#introduction for more details

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)]

Laravel - Validate value against string

I am running some basic validation inside a Laravel 5.5 controller like this...
$this->validate($request, [
'name' => 'required|max:30',
'email' => 'required|unique:users|email',
'password' => 'required|max:20',
'mykey' => 'required',
]);
Is there a way to check if 'mykey' matches a php string I have saved? I know I can do an if statement and compare them but wondered if there was a way I could do this inside the validation itself?
You can use in rule, This works for n number of values
$request->validate([
'name' => 'required|max:30',
'email' => 'required|unique:users|email',
'password' => 'required|max:20',
'mykey' => [
Rule::in([env('MY_KEY'),config('app.another_key')]),
]
]);
Laravel provides a regex option for validation. Depending on the complexity of the string comparison it may be useful:
https://laravel.com/docs/5.5/validation#rule-regex
You can this rule:
$key = "my_saved_key"
$request->validate([
'name' => 'required|max:30',
'email' => 'required|unique:users|email',
'password' => 'required|max:20',
'mykey' => 'in:' . $key,
]
]);

Laravel assign User ID when registering

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
]);

Resources