Laravel Date assign errorr - laravel

I have small problem in app. Backend is Laravel and Front end is Nuxtjs.
When User registered on app,then users must be wait antill Administartor approved.
When Admin approved this user we give them 3 months subscription.
In my code this part is not working.
$user->activated_at = now();
$user->activated_at = date('Y-m-d H:i');
{
$user = User::find($id);
if (is_null($user)) {
return $this->sendError('admin_messages.user_not_found');
}
$user->status = User::ACTIVE;
$user->activated_at = now();
$user->activated_at = date('Y-m-d H:i');
dd($user->activated_at);
$user->save();
Mail::to($user->email)->queue(new ApproveNotificationMail($user));
return $this->sendResponse('admin_messages.user_activated');
}

$user->activated_at = \Carbon\Carbon::now()->format('Y-m-d H:i');

You can use mutator in your User model, to force activated_at format:
public function setActivatedAtAttribute( $value ) {
$this->attributes['activated_at'] = (new Carbon($value))->format('Y-m-d H:i');
}
You can define a format for date columns using:
protected $dateFormat = 'Y-m-d H:i';
Note that you can directly use:
$user->activated_at = \Carbon\Carbon::now()->format('Y-m-d H:i');

Related

Customize Laravel 8 Passport methods

The login validation I use is not Laravel's default. How do I customize Passport methods?
The following code I use to validate with web middleware.
$username = $request->username;
$password = strtoupper(md5($request->password));
$system = env("CODE_SYSTEM", 12);
$sql = "SELECT user.validate( '$system' , '$username', '$password')";
$stmt = DB::select(DB::raw($sql));
$result = $stmt[0]->validation;
if ($result == "ok") {
$user = new User();
$id = DB::table('users')->select('id')
->where('username' , $username)->first();
$user = User::find($id->id);
return $user;
}
To customize you need add the validateForPassportPasswordGrant() at User method, example:
public function validateForPassportPasswordGrant($password)
{
$password = strtoupper(md5($request->password));
$system = env("CODE_SYSTEM", 12);
$sql = "SELECT user.validate( '$system' , '$this->username', '$password')";
$stmt = DB::select(DB::raw($sql));
$result = $stmt[0]->validation;
if ($result == "ok") {
return true;
}
return false;
}
If you need to change the user column name where the passport search username:
public function findForPassport($username)
{
return $this->where('the_username_column', $username)->first();
}

How can I store the web push notification settings after the login in database

I want to send web push notification on the browser. I used this tutorial to
send the notification. This is working fine and show the details.
{
"endpoint":"https://fcm.googleapis.com/fcm/send/ftB1OYn5bJY:APA91bGNcquGDcUXr29JiVV5Zos4Vi7FzmZ_wJQMITEXt8FlVBRBtgrPdLnPR6GALtnCOe9RNPP1cmC_bkv9D1BE1o6_-0cMXQsodpPoRCeOP5EDt6EwqK0ys36MbCi3HNTWf7ZcItVi",
"expirationTime":null,
"keys":{"p256dh":"BLJQqNovnlJ28d5xteX8whwdby6l0BYLvC_iyNtY2nO7YXQSI-EOvdOs1LXy8F_EuH2MZi0FU_HoCO-5GRQYYVQ",
"auth":"tDcEgiy5M5tJ3_vXuuQ9uw"}
}
but I want to integrate with my Laravel API.
After the user login, I want to save the endpoint, public key, and auth
to the database.
Login Controller
public function authenticate(Request $request)
{
$credentials = $request->only('username', 'password');
// return $credentials;
$response = array(
'status' => 'Failed',
'msg' => '',
'is_success' => false,
'data' => ''
);
try {
if (!$token = JWTAuth::attempt($credentials)) {
$response["msg"] = "Wrong Username or Password";
$response["status"] = "Failed";
$response["is_success"] = false;
} else {
if (Auth::user()->is_active == 0) {
$response["msg"] = "Your account has not been activated";
$response["status"] = "Failed";
$response["is_success"] = false;
} else {
$data = array();
$user = User::find(Auth::user()->id);
$data['id'] = $user->id;
$data['fname'] = $user->fname;
$data['lname'] = $user->lname;
$data['email'] = $user->email;
$data['username'] = $user->username;
$response["msg"] = "Login Successfully";
$response["status"] = "Success";
$response["data"] = compact('token');
$response["user"] = Auth::user();
}
}
} catch (\Exception $th) {
$response["msg"] = $th->getMessage();;
$response["status"] = "Failed";
$response["is_success"] = false;
}
return $response;
}
I think the best way to solve this, is to make another model for that data, a one to one relationship between user model and push notification data model. Make a controller for CRUD operations on this new model, and just have another http call from the front end to store the data.

A simple event listener in laravel

I have a small app that I don't see it growing beyond a couple of pages so for an event, I decided to have the event in the router web.php
This is the code
Event::listen('simpleEvent', function($user){
$user->last_login = new DateTime;
$user->save();
});
I want to use the event on a particular method
public function getLogin(){
$user = User::find(1);
$device = $agent->device();
$platform = $agent->platform();
$browser = $agent->browser();
$ip = Request::ip();
Event::fire('simpleEvent','[$user]);
}
My question is, how do I pass the variables from getLogin to the event in the router?. Right now I am only passing the user
Just wrap the data you need to pass in an array.
Event::listen('simpleEvent', function($data) {
// dd($data);
});
public function getLogin()
{
$user = User::find(1);
$device = $agent->device();
$platform = $agent->platform();
$browser = $agent->browser();
$ip = Request::ip();
$data = compact('user', 'device', 'platform', 'browser', 'ip');
Event::fire('simpleEvent', $data);
}

Using with() and find() while limiting columns with find cancels relation data

I have the following code that displays different data depending on if you are the authenticated user looking at your own data or if you are looking at data from another user. The code works but in my opinion is very nasty.
public function showUserDetailed(Request $request, $username)
{
$key = strtolower($username).'-data-detailed';
if(Auth::user()->usenrame === $username) {
$key = $key .'-own';
}
if(Cache::has($key)) {
if($request->wantsJson()) {
return request()->json(Cache::get($key));
} else {
return view('user/detailed', ['user' => Cache::get($key)]);
}
} else {
if(Auth::user()->username === $username) {
$u = User::where('username', $username)->first();
$user = new \stdClass();
$user->username = $u->username;
$user->email = $u->email;
$user->address = $u->address;
$user->city = $u->city;
$user->state = $u->state;
$user->zip = $u->zip;
$user->phone = $u->phone;
$user->follows = $u->follows;
$user->ratings = $u->ratings;
$user->location = $u->location;
} else {
$u = User::where('username', $username)->first(['username', 'city', 'state']);
$user = new \stdClass();
$user->username = $u->username;
$user->city = $u->city;
$user->state = $u->state;
$user->follows = $u->follows;
$user->ratings = $u->ratings;
}
Cache::put($key, $user);
if($request->wantsJson()) {
return response()->json($user);
} else {
return view('user/detailed', ['user' => $user]);
}
}
}
I have tried to use something similar to the following in the model calls.
User::where('username', $username)->with('follows', 'ratings', 'location')->find(['username', 'city', 'state');
However when I specify the columns to get from the user table it negates the relation data so it comes back as empty arrays. Is there a different way I can do this which would be cleaner? I despise having to create a stdClass to be a data container in this situation and feel I may be missing something.
// this works
User::where('username', $username)->with('follows', 'ratings', 'location')->first();
// this also works
User::where('username', $username)->first(['username', 'city', 'state']);
// this does not
User::where('username', $username)->with('follows', 'ratings', 'location')->first(['username', 'city', 'state']);
When you specify columns and want to get the related models as well, you need to include id (or whatever foreign key you're using) in the selected columns.
The relationships execute another query like this:
SELECT 'stuff' FROM 'table' WHERE 'foreign_key' = ($parentsId)
So it needs to know the id of the parent (original model). Same logic applies to all relationships in a bit different forms.

Session always returns null facebook php sdk

Hi I'm trying to get data from a user from facebook after he logs in whit facebook. But my session variable is always null .I'm currently using the laravel 4 framework. The code that you are seeing is being called as the callback function from facebook login.
$code = Input::get('code');
if (strlen($code) == 0) return Redirect::to('/')->with('message', 'There was an error communicating with Facebook');
$facebook = new Facebook(Config::get('facebook'));
$uid = $facebook->getUser();
if ($uid == 0) return Redirect::to('/')->with('message', 'There was an error');
$me = $facebook->api('/me');
$profile = Profile::whereUid($uid)->first();
if (empty($profile)) {
$user = new User;
$user->name = $me['first_name'].' '.$me['last_name'];
$user->email = $me['email'];
$user->save();
$profile = new Profile();
$profile->uid = $uid;
return $uid;
$profile->username = $me['name'];
$profile = $user->profiles()->save($profile);
}
$profile->access_token = $facebook->getAccessToken();
$profile->save();
$user = $profile->user;
Auth::login($user);
FacebookSession::setDefaultApplication(
Config::get('facebook.appId'),
Config::get('facebook.secret')
);
$helper = new FacebookRedirectLoginHelper('http://projectweb.app:8000/');
$session = $helper->getSessionFromRedirect();
if(isset($session))
{
$request = new FacebookRequest($session,'GET','/me');
$response = $request->execute();
$graph = $response->getGraphObject(GraphUser::classname());
$name = $graph->getName();
return $name;
}
else
{
return 'no sesssion';
}
You better try using a Laravel specific Package for that, here it is one, where you also have the details about installing and using it.
https://github.com/SammyK/LaravelFacebookSdk

Resources