A simple event listener in laravel - 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);
}

Related

Laravel Date assign errorr

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

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.

How to write Laravel eloquent query inside model function?

Actually I don't know how to retrieve data from db using function and query inside model .Please help me what should i add inside model function.
Here is controller
public function checkAdmin(Request $request){
$data = array();
$data['email'] = $request->email;
$data['password'] = $request->password;
$found = AdminModel::checkAdmin($data);
if($found == TRUE){
echo "found";
}
else{
echo "sorry";
}
}
Here is the Model Function
public static function checkAdmin($data){
$found = $this->where('email',$data['email'])->where('password',$data['password'])->first();
return $found;
}
What is the purpose of the checkAdmin function? Are you trying to validate a login? If yes, Laravel does this for you out of the box with the Auth::attempt method:
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
// Authentication passed...
return redirect()->intended('dashboard');
}
https://laravel.com/docs/5.7/authentication#authenticating-users
However to answer your question, you could do so like this:
$userFound = AdminModel::where(['email' => $request->email, 'password] => $request->password)->count();
if($userFound){
echo "found";
}
else{
echo "sorry";
}

why the session is lost after redirect in laravel 5.5?

I implementing a payment gateway with flywire in laravel.
i have a method that update a data to a crm without problem, i need this data when is called to another method that make a redirect to a external url (is a wizard) the trouble is that after maked the redirection the value of sessions are lost.
How can I holding those values ​​after redirecting to an external url?
use Session;
public function update(Request $request)
{
//code..
Session::put('value1',$request->val1);
Session::put('value2',$request->val2);
$url = 'https://www.urldemo.payment.com/payment/';
$data=[
'value1'= $request->val1,
'value2' = $request->val2,
];
$params = json_encode($data);
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl,CURLOPT_POST,true);
curl_setopt($curl,CURLOPT_POSTFIELDS,$params);
try{
$response = curl_exec($curl);
$info = curl_getinfo($curl);
$err = curl_error($curl);
curl_close($curl);
return response()->json(['success'=>'the update was completed success','url'=> $url],200);
}catch(Exception $e){
return response()->json(['errors'=> $e->getMessage()],422);
}
}
/*This function retrieve the response data from the payment update*/
public function returnData(Request $request){
$obj = json_decode($request->getContent());
if(Session::exists('value1')){
$p1 = $obj->id;
}elseif(Session::exists('value2')){
$p2 = $obj->id;
}else{
$p1 = '';
$p2 = '';
}
$data2 = [
'value1' => $p1,
'value2' => $p2,
];
$values = json_encode($data2);
dd($values);
/*Here print the $p1 and $p2 empty thats after redirect to a external url the point is that here the session is lost*/
}
My question at this moment is how can i hold the sessions after redirect in Laravel 5.5 ?

Laravel controller, move creating and updating to model?

my question is about how to split this code. I have a registration form and it's saving function looks like this:
public function store(EntityRequestCreate $request)
{
$geoloc = new Geoloc;
$geoloc->lat = $request->input('lat');
$geoloc->lng = $request->input('lng');
$geoloc->slug = $request->input('name');
$geoloc->save();
$user_id = Auth::id();
$entity = new Entity;
$entity->name = $request->input('name');
$entity->type = $request->input('type');
$entity->email = $request->input('email');
$entity->tags = $request->input('tags');
$entity->_geoloc()->associate($geoloc);
$entity->save();
$entity_id = $entity->id;
$address = new Address;
$address->building_name = $request->input('building_name');
$address->address = $request->input('address');
$address->town = $request->input('town');
$address->postcode = $request->input('postcode');
$address->telephone = $request->input('telephone');
$address->entity_id = $entity_id;
$address->save();
$role = User::find($user_id);
$role->role = "2";
$role->save();
DB::table('entity_user')->insert(array('entity_id' => $entity_id, 'user_id' => $user_id));
$result = $geoloc->save();
$result2 = $entity->save();
$result3 = $address->save();
$result4 = $role->save();
if ($result && $result2 && $result3 && $result4) {
$data = $entity_id;
}
else {
$data = 'error';
}
return redirect('profile/entity');
}
As you see, it has a custom request and it is saving to 3 models, that way my controller code is far too long (having many other functions etc) Instead I want to move this code to a model, as my model so far has only relationships defined in it. However I don't exactly know how to call a model from controller, do I have to call it or it will do it automatically? Any other ideas on how to split the code?
You could use the models create method to make this code shorter and more readable.
For example:
$geoloc = Geoloc::create(
$request->only(['lat', 'lng', 'name'])
);
$entity = Entity::create(
$request->only(['name', 'type', 'email', 'tags])
);
$entity->_geoloc()->associate($geoloc);
$address = Address::create([
array_merge(
['entity_id' => $entity->id],
$request->only(['building_address', 'address', 'town'])
)
])
...
The create method will create an object from a given associated array. The only method on the request object will return an associated array with only the fields for the given keys.

Resources