Using Laravel firstOrCreate function to search in two columns - laravel

how can I check two columns with firstOrCreate function? I need to work this like where('email', $request->email)->orWhere('personal_code', $request->personal_code), not like where('email', $request->email)->where('personal_code', $request->personal_code)
$user = User::firstOrCreate(
[
'email' => $request->email,
'personal_code' => $request->personal_code,
],
[
'name' => $request->tenant,
'phone' => $request->phone,
'address' => $request->address
]
);
Thanks for help in advance!

You won't be able to run an or within the firstOrCreate() method.
To achieve this, you would need to create using custom functionality:
$user = User::where('email', $request->email)
->orWhere('personal_code', $request->personal_code);
$user = $user->exists()
? $user->first()
: User::create($request->only(['email', 'personal_code', 'name', 'phone', 'address']));
// or $request->expect('_token') if all data passed via form.

Related

Multiple inputs in one validation rule

return [
'contract_code' => 'required',
'name' => 'required|string',
'abbreviation' => 'required|string',
'linecount_divisor' => 'required|integer'
];
// into input fields => 'required'
How to shorten the validation rule in multiple inputs?
if You have the same validation rule for multiple and you want to shorten your code just use form requests.
php artisan make:request RequestName
And then in the controller Functions use it
public function save(RequestName $requestName)
{
}
don't forget to use that request class.
use App\Http\Requests\RequestName;
Here is a solution assuming all input fields need to have a common rule like required.
$rules = array_map(function($curr) { return [$curr => 'required']; }, array_keys(request()->all()));
Try this one in Laravel
$validation=array();
$validation= [
'contract_code' => 'required',
'name' => 'required|string',
'abbreviation' => 'required|string',
'linecount_divisor' => 'required|integer'
];
$this->validate($request,$validation);

Laravel one validation function for Store and Update

I am trying to have one validation function for both store and update. So I don't repeat code. It works well. The problem is testing 'unique'. I worked around with this idea. But feels long-winded. Is there a better way to do it?
I want to check for unique at the store.
At update, unique check ignores own id.
I don't want different validations like I did as the user will be
first notified of the unique error, he will fix it. then something
else might be wrong and he has to fix again.
.
public function validateRequest($request){
if($request->method() == "PUT")
{
$val = $this->validate($request, [
'name' => 'unique:customers,id',
'phone' => 'unique:customers,id',
]);
}
if($request->method() == "POST"){
$val = $this->validate($request, [
'name' => 'unique:customers',
'phone' => 'unique:customers'
]);
}
$validation = $this->validate($request, [
'name' => 'required',
'phone' => 'required|integer|gt:0',
'phone2' => 'nullable|integer|gt:0|',
'email' => 'email|nullable',
'note' => 'nullable',
],
[
'phone.integer' => "Invalid phone format. Use international format. Eg: 971550000000",
'phone2.integer' => "Invalid phone format. Use international format. Eg: 971550000000",
'required' => "Required Field",
]);
return $validation;
}

Creation of related Models on auth RegisterController in laravel

In my application, I have tables related to users and some of these tables require a row be inserted as soon as a User is registered.
For example, I have the following models:
UserProfile,
UserAssignedRole,
UserSettings
As soon as a User successfully registers, they will need a corresponding row in the DB.
I've done the following:
protected function create(array $data)
{
$user = User::create([
'username' => $data['username'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
UserProfile::create([
'user_id' => $user->id,
]);
UserAssignedRole::create([
'user_id' => $user->id,
'role_id' => 1
]);
UserSettings::create([
'user_id' => $user->id,
'nsfw' => 1
]);
return $user;
}
I'm looking for a better and more elegant way to achieve this. Is there a "Laravel" way in achieving this?
In the Larvel docs there's a chapter about Recursively Saving Models & Relationships. This is probably what you're looking for. They specify the following example:
$post = App\Post::find(1);
$post->comments[0]->message = 'Message';
$post->comments[0]->author->name = 'Author Name';
$post->push();
You could achieve something similar by creating a user including all its relationships in one push().

Laravel 5.5 Validation with OR/ELSE conditional

i'm new to laravel and i would like to know if there are a way to use or/else conditional in $rules, because I am struggling trying to do the following validation:
If the field is Z the size must be y, else, x.
I tried this, but it always validade data with size:11
'type => 'required',
'field' => ['required', ('type == 1' ? 'size:11' : 'size:14')],
Anyone has a clue? thanks in advance
I assume you use Form request validation so you can do something like this:
$rules = [
'type' => 'required',
'field' => ['required'];
];
$rules['field'][] = ($this->input('type') == 1) ? 'size:11' : 'size:14';
return $rules;
Use Laravel Validator ,
Refer Link: https://laravel.com/docs/5.5/validation
$validatedData = $request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);

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