Auth::attempt() Manually Authenticating Users based on NULL condition | Laravel | Passport - laravel

I am creating an application based on Laravel 5.8. I want to manually authentication users based on some checks, But these checks or fields have some null values or not null values.
I follow the official documentation Link
Instead of checking like this
if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
// The user is active, not suspended, and exists.
}
I want to check if some fields that are not null like
if (Auth::attempt(['email' => $email, 'password' => $password, 'activate_on' => 'SomeDateTimeValue Or Not Null' ])) {
}
So it means if the user has some activate_on fields value which should not Null then the Auth::attempt should return true otherwise false.

You can do it by adding your implementation of the UserProvider interface, but that's a lot of work.
I think the easiest way is to do it in two steps.
// first get the user by email
$user = User::whereEmail($email)->first();
if($user->activate_on && Auth::attempt(['email' => $email, 'password' => $password])
{
// logged in
}

I do not believe what you are asking is directly possible. If you take a look at the retrieveByCredentials() method which is called during the attempt() process, the query builder is only set up to accept a value where($key, $value) or an array of values whereIn($key, $value) to conditionally query the user.
public function retrieveByCredentials(array $credentials)
{
if (empty($credentials) ||
(count($credentials) === 1 &&
array_key_exists('password', $credentials))) {
return;
}
// First we will add each credential element to the query as a where clause.
// Then we can execute the query and, if we found a user, return it in a
// Eloquent User "model" that will be utilized by the Guard instances.
$query = $this->newModelQuery();
foreach ($credentials as $key => $value) {
if (Str::contains($key, 'password')) {
continue;
}
if (is_array($value) || $value instanceof Arrayable) {
$query->whereIn($key, $value);
} else {
$query->where($key, $value);
}
}
return $query->first();
}
EDIT:
Sample helper function:
if (!function_exists('attempt')) {
function attempt($credentials, $dates = [], $remember = false)
{
$user = User::where('email',$credentials['email'])->first();
// if a date is null return false
foreach ((array)$dates as $date) {
if (is_null($user->{$date})) {
return false;
}
}
return Auth::attempt($credentials, $remember);
}
}
Usage:
// single date
if (attempt(['email' => $email, 'password' => $password],'activate_on')) {
// ...
}
// array of dates
if (attempt(['email' => $email, 'password' => $password],['activate_on','approve_on'])) {
// ...
}
// no date
if (attempt(['email' => $email, 'password' => $password])) {
// ...
}

Related

set array_filter to accept null, zero and empty values

How can I set "array_filter" to accept the null values, empty and zero?
I tried the callback function but it didn't work for me.
Here's my code
$student = array_filter($request->student);
$teacher = array_filter($request->teacher);
$ScID = array_map(null, $student, $teacher);
SchoolDescriptions::where('pin_id', $request->session()->get('pin_id'))->delete();
foreach ($ScID as $key=>$array) {
SchoolDescriptions::updateOrCreate([
'student' => $array[0],
'teacher' => $array[1],
'pin_id' => $request->session()->get('pin_id')
]);
}; return back()->withStatus(__('Successfully saved.'));
I was able to find a solution for this. So I just simply made a condition.
To accept null values when submitting teacher and student forms.
if ($request->student == null && $request->teacher == null)
{
//do nothing
}
else {
$student = array_filter($request->student);
$teacher = array_filter($request->teacher);
$ScID = array_map($student, $teacher);
SchoolDescriptions::where('pin_id', $request->session()->get('pin_id'))->delete();
foreach ($ScID as $key=>$array) {
SchoolDescriptions::updateOrCreate([
'student' => $array[0],
'teacher' => $array[1],
'pin_id' => $request->session()->get('pin_id')
]);
};
}

Return to view from another function in laravel

Hi I'm saving information from blade. The form goes to store function. After saving data I have to send push info using GCM. But this function can not return to view. How can solve this?
public function store(Request $request)
{
$request->validate([
'title_uz' => 'required',
'desc_uz' => 'required',
'url_uz' => 'required',
'company_id' => 'required',
]);
News::create($request->all());
$this->versionUpdate();
$this->sendpush($request);
}
And next function
public function sendpush (Request $request)
{
$fcmUrl = 'https://fcm.googleapis.com/fcm/send';
$notification = [
'title' => $request->title_uz,
'text' => $request->desc_uz,
];
***** here is some functions *******
$result = curl_exec($ch);
curl_close($ch);
$result_to = json_decode($result);
if ($result_to === null) {
return redirect()->route('news.index')
->with('success','DIQQAT!!! Yangilik qo`shildi ammo push-xabar yuborilmadidi.');
}
else {
return redirect()->route('news.index')
->with('success','Yangilik qo`shildi va push-xabar muvoffaqiyatli yuborildi.');
}
}
$result_to returns value but the browser holds at blank screen. It seems the store function holds at the end.
Try this line return $this->sendpush($request);instead of this $this->sendpush($request);
you have redirect from this method so you can try like these
$result_to = $this->sendpush($request);;
if ($result_to === null) {
return redirect()->route('news.index')
->with('success','DIQQAT!!! Yangilik qo`shildi ammo push-xabar yuborilmadidi.');
}
else {
return redirect()->route('news.index')
->with('success','Yangilik qo`shildi va push-xabar muvoffaqiyatli yuborildi.');
}

Auth::attempt(['email' => Request::input('email') dont work?

I want to make auth with Laravel 5.0 but I entered true data or false data give the error
public function girispost(){
//return Request::input('email') .Request::input('password');
// Auth::logout();`
if (Auth::attempt(['email' =>
Request::input('email'), 'password' => Request::input('password')])) {
return "giriş başarılı";
} else {
return "hatalı";
}
}
users table scheme

Using pluck() helper function in laravel

I'm building a small application on laravel 5.5 where I'm getting a list of multiple users with there information, from the forms as below format:
{
"name":"Test",
"description":"Test the description",
"users":[
{
"value":"XYZabc123",
"name":"Nitish Kumar",
"email":"nitishkumar#noeticitservices.com"
},
{
"value":"MFnjMdNz2DIzMJJS",
"name":"Rajesh Kumar Sinha",
"email":"rajesh#noeticitservices.com"
}
]
}
I just want to get the value key form the users array via laravel collection something like this:
$userIds = $request->users->pluck('value');
so that I can put them into query:
$user = User::all()->whereIn('unique_id', $userIds);
May be I'm doing most of the things wrong but my main motive is to use laravel collection or helper functions and make a cleaner code for this:
$teamData['name'] = $request->name;
$teamData['description'] = $request->description;
$teamData['unique_id'] = str_random();
$users = $request->users;
$team = Team::create($teamData);
if($team)
{
$userIds = [];
foreach ($users as $user)
{
$getUser = User::where('unique_id', $user['value'])->get()->first();
$userIds [] = $getUser->id;
}
$team->users()->attach($userIds);
return response()->json(['message' => 'Created Successfully'], 200);
}
return response()->json(['message' => 'Something went wrong'], 500);
I'm still learning collections, any suggestions is appreciated. Thanks
Data that come from $request (form) isn't a collection. It's an array. If you need it to be collection, you should convert it to collection first.
PS. If you have multiple DB actions in single method, It's good to have DB transaction.
\DB::transaction(function () use ($request) {
// convert it to collection
$users = collect($request->users);
$team = Team::create([
'name' => $request->name,
'description' => $request->description,
'unique_id' => str_random(),
]);
$team->users()->attach($users->pluck('value')->toArray());
});
// HTTP Created is 201 not 200
return response()->json(['message' => 'Created Successfully'], 201);
or you'll need something like this:
return \DB::transaction(function () use ($request) {
$users = collect($request->users);
$team = Team::create([
'name' => $request->name,
'description' => $request->description,
'unique_id' => str_random(),
]);
$team->users()->attach($users->pluck('value')->toArray());
return response()->json([
'message' => 'Created Successfully',
'data' => $team,
], 201);
});
I just want to get the value key form the users array via laravel collection
Just use map then:
$userIds = $request->users->map(function($user) {
return $user->value; // or $user['value'] ? not sure if this is an array
});
Edit:
if $request->users is not a collection, make it one before calling map:
$users = collect($request->users);
$userIds = $users->map(function($user) {
return $user->value; // or $user['value'] ? not sure if this is an array
});

CakePHP custom Validation rule checks unique field combination only on create

I have a Database with a User model. These Users should be unique by their name and birthday.
So I wrote a custom validation function called checkUnique
public function checkUnique($check){
$condition = array(
"User.name" => $this->data["User"]["name"],
"User.lastname" => $this->data["User"]["lastname"],
"User.birthday" => $this->data["User"]["birthday"]
);
$result = $this->find("count", array("conditions" => $condition));
return ($result == 0);
}
The validation rule in the model:
"name" => array(
"checkUnique" => array(
"rule" => array("checkUnique"),
"message" => "This User already exists.",
"on" => "create"
),
)
I have two problems.
The first: This validation rule also triggers on update action, implemented as
public function edit($id = null) {
if (!$this->User->exists($id)) {
throw new NotFoundException(__('Invalid User'));
}
if ($this->request->is(array('post', 'put'))) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('Update done.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user can't be saved.'));
}
} else {
$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
$this->request->data = $this->User->find('first', $options);
}
}
But I wrote "on" => "create", so why it triggers also on update?
The second problem:
If the validation rule only triggers on create, how can I manage, to trigger an validation error, if someone change the name, lastname and birthday like an other user in the Database? Then the unique validation rule should be triggered.
Remove the 'on' => 'create'. (You want to validate in both events).
Modify your custom validation rule to this
public function checkUnique() {
$condition = array(
"User.name" => $this->data["User"]["name"],
"User.lastname" => $this->data["User"]["lastname"],
"User.birthday" => $this->data["User"]["birthday"]
);
if (isset($this->data["User"]["id"])) {
$condition["User.id <>"] = $this->data["User"]["id"];
//your query will be against id different than this one when
//updating
}
$result = $this->find("count", array("conditions" => $condition));
return ($result == 0);
}

Resources