Learnings Posts
How to Delete Record using ajax call with LaravelLaravel
How to Delete Record using ajax call with LaravelLaravel
We work on projects with the admin panel every day. In which we mostly use data tables and we need to delete the record from the data table without page refresh.
So, today I will show you how to extract a record using Ajax. It's very easy to integrate.
Let's take one example. I have a Category data table and I want to delete one category from the table without refreshing the page. Now, what am I doing for that? First of all, I add a class for the listen to a click event into the delete button and it says delete-btn.
See the following image for where I added a class.
I used SweetAlert for the confirmation popup. let add sweet alert's CSN into the index.blade.php.
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script>
Let's declare routes of the delete record.
<script>let categoryUrl = '{{route('categories.index')}}'; </script>
Next steps, I'm going to listen to the click event of the delete button. one more thing does not forget to add the record id into the data attribute to the delete button. see the above image for it. I highlighted it with a yellow line.
So the general practices we use in Laravel is to write the following code to listen to a click event and delete a record,
$(document).on('click', '.delete-btn', function (event) {
const id = $(event.currentTarget).data('id');
swal({
title: 'Delete !',
text: 'Are you sure you want to delete this Category" ?',
type: 'warning',
showCancelButton: true,
closeOnConfirm: false,
showLoaderOnConfirm: true,
confirmButtonColor: '#5cb85c',
cancelButtonColor: '#d33',
cancelButtonText: 'No',
confirmButtonText: 'Yes', },
function () {
$.ajax({
url: categoryUrl + '/' + id,
type: 'DELETE',
DataType: 'json',
data:{"_token": "{{ csrf_token() }}"},
success: function(response){
swal({
title: 'Deleted!',
text: 'Category has been deleted.',
type: 'success',
timer: 2000,
});
$('#categoryTbl').DataTable().ajax.reload(null, false);
},
error: function(error){
swal({
title: 'Error!',
text: error.responseJSON.message,
type: 'error',
timer: 5000,
})
}
});
});
});
Now we are done with the front-end side and need to look into it backend side.
Let's declare the destroy method into the category Controller. I hope are you generating crud with InfyOm Laravel Generator. so, the Destroy method and routes are there. If not please create a route. if the destroy method is there then need to change the response of that method.
The destroy method code looks like,
public function destroy($id) {
$category = $this->categoryRepository->find($id);
if (empty($category)) {
Flash::error('Category not found');
return $this->sendError('Category not found.');
}
$this->categoryRepository->delete($id);
return $this->sendSuccess('Category deleted successfully.');
}
How to Keep Your Customers Happy & Increase Repeat Project - 2Sales
How to Keep Your Customers Happy & Increase Repeat Project - 2Sales
Here is part one of How to Keep Your Customers Happy & Increase Repeat Project
9. Know your products and services
Customers want to work with knowledgeable employees. Learn all you can about your products so you can be better equipped to answer customer questions. If you are unsure about something, ask for help.
10. Treat your customers individually
Not all customers are the same. Every customer has individual needs and concerns and they want to be treated with a personal touch that doesn’t make them feel like a number. Communicate the way your customers want to communicate.
11. Make it easy for your customers to complain
Your customers seem to have heard, especially when they are frustrated with the service they have received. Customers know what they like and at least about your service. Ongoing surveys are a reliable and consistent approach to getting feedback but don’t miss the opportunity when you’re with a customer. Just asking you sends a beautiful message about how you value your customers and their feedback.
12. Thank your customers for every opportunity you get
Thank you very much for your customers. Thank you for calling, bringing payment, meeting you at their home, calling for help, and yes, calling for a complaint! For many, there are options available and they chose your company over the competition.
13. Never accept your customers
Your customers are your business!
14. To be active
Don't wait for your client to reach you. Reach out to them in more than one way. Improving the first call resolution cases of the customer problem will improve the overall customer experience. Create a complete self-help interface, in which customers can solve their problems manually.
15. I will take responsibility
Tell your customer that you understand that you have a responsibility to ensure a satisfactory outcome of the transaction. Assure the customer that you know what she expects and will deliver the product or service at the agreed price. There will be no unexpected charges or costs to solve the problem.
Company Culture:“It’s the backbone of any Successful Organisation”Human Resource
Company Culture:“It’s the backbone of any Successful Organisation”Human Resource
- Freedom to communicate.
- It signifies the transparency of the environment in the organization.
- It helps to improve the implementation of any system & bring innovation by free interaction among team members, clarity in setting objects, and common Goals.
- Facing problems and challenges.
- The person is facing it boldly and not shying.
- Improve Problem Solving.
- Clarity in work.
- Group discussion to resolve particular problems.
- Maintaining confidentiality.
- Building trust in each other.
- Do not share anything to others or outside of the organization.
- Higher Empathy.
- Timely Support.
- Reduce Stress.
- No or narrowest gap between said value & Actual behaviour.
- Person’s commitment to work/Assigned tasks & Actual performance should be the same.
- Everyone has attitude “Jo me bolta hu wo me karta hu”
- Develop mutuality culture.
- Sharing of feeling freely.
- Improve interpersonal communication.
- Reduce the distortion in Communication.
- Taking Initiative.
- Pre- Planning.
- It prepared everyone for upcoming challenges.
- Reduce uncertainty.
- One step ahead (advance team)
- Prepare everyone to accept changes with time.
- Freedom to plan & act at one’s own level.
- Organisation must avoid an Autocratic type of environment and give chance to all members to use their power in a positive way.
- Develop mutual relationship.
- Feeling of Pride.
- Self Motivation
- work satisfaction.
- Involves working together for common cause.
- individuales share their concerns and prepare strategies for working out plans, actions & implementing them together.
- Timely work.
- Resource sharing.
- Improve Communication.
- Trying out new ways to deal with problems/Tasks.
- Organisation should allow all to experiment new ways and encourage them to find the best ways.
- Accurate problem solutions.
- Development of new products.
- Development of New methods.
To recapitulate, Organisational culture represents Values, Beliefs, behaviors & Capabilities acquired by the members of the firm. We can truly say if the Organisation has all Dimensions of __“OCTAPACE”,__ it is on the way to __SUCCESS__……….
Facebook Login With Firebase In Android JavaAndroid Development
Facebook Login With Firebase In Android JavaAndroid Development
1.Add this library build.gradle(:app)
- This library user for firebase integration dependencies
{
implementation 'com.google.firebase:firebase-auth:19.4.0'
}
2.Add this permission in AndroidManifest.xml
- This permission use internet connection checking
{
<com.facebook.login.widget.LoginButton
android:id="@+id/login_button"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:visibility="gone"/>
}
3.Activity in add this permission
- This permission is for user data. Without this permission user data not meet
- loginButtonThis button is Facebook button
- LoginManager.getInstance().logInWithReadPermissions(FacebookLoginActivity.this, Arrays.asList("email", "public_profile"));
- loginButton.setReadPermissions("email", "public_profile");
4.Initialize Authentication:
void initializeAuthentication(){
FirebaseAuth mAuth = FirebaseAuth.getInstance();
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, so);
}
7.Add This Function:
- This function user login result return
void faceBookLogin(LoginResult loginResult){
setFacebookData(loginResult);
Profile profile = Profile.getCurrentProfile();
if (profile != null) {
String avatar = ImageRequest.getProfilePictureUri(profile.getId(), 200, 200)
.toString();
} handleFacebookAccessToken(loginResult.getAccessToken());
}
7.Handle Token :
- This token return firebase login fails or not an event
private void handleFacebookAccessToken(AccessToken token) {
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful()) {
FirebaseUser user = mAuth.getCurrentUser();
user.getIdToken(true).addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
String token = task.getResult().getToken();
}
});
} else {
String errorCode = String.valueOf(task.getException());
Toast.makeText(FacebookLoginActivity.this, "Login failed.", Toast.LENGTH_SHORT).show();
}
}
});
}
Notes:
- “Default_web_client_id” this keyword, not changes because creating google-services.json file time automatically this keyword in add values so this key work put at its
How to Integrate the Stripe Customer PortalLaravel
How to Integrate the Stripe Customer PortalLaravel
The Stripe Customer Portal is very useful for managing customer subscriptions like Upgrade, Downgrade, and Renew.
Customers can review their invoices directly and also check their history.
Portal billing setting
Do login into your stripe account
Navigate to the portal settings to configure the portal, and do below billing settings
Create Product
First of all, we need to create products. Follow the below process for creating products.
Click on the “Products” menu from the sidebar and click on the “Add Product” button on the top right corner of the products page and create a product.
Here is an example of how to create a product.
Create two or three products as shown below.
Select product In portal settings
If you want to allow your customer to change their subscription by an upgrade, downgrade, cancel or renew you need to set products in your portal setting.
Now navigate to customer portal settings again, in the Products section, you will find a dropdown “Find or add a product..”, click on it you will find the plan you have added, select the price of this product.
Don’t forget to save all these settings.
Then do the setup of your business information, also do branding settings in the “Appearance” section, and save it.
Once you are done with settings, you can preview the customer portal by clicking the Preview button beside the save button.
This will launch a preview of the portal so you can see how customers will use it for managing their subscriptions and billing details.
Integrate into Laravel
- Get you API keys
- Go to “Developers > API keys” here you will find your “Publishable key” and “Secret key
- Create customer using stripe dashboard or by API
- Create customer by Stripe API.
- First of all, you’ll need to set your stripe secret key. For development mode, you can use test mode keys, but for production, you need to use your live mode keys
\Stripe\Stripe::setApiKey('sk_test_YOUR_KEY');
$customer = \Stripe\Customer::create([undefined]);
- Once you create a customer using stripe API, now you can create a billing session for that customer using stripe API.
- Create a billing session of the customer by API
\Stripe\Stripe::setApiKey('sk_test_YOUR_KEY');
\Stripe\BillingPortal\Session::create([
'customer' => 'cus_HnKDAQNjBniyFh',
'return_url' => 'https://example.com/subscription'
]);
You’ll get a response, like the below object:
{
"id": "pts_c5cfgf8gjfgf73m5748g6",
"object" : "billing_portal.session",
"created" : 453543534,
"customer" : "cus_bGFsnjJDcSiJu",
"livemode" : false,
"return_url": "https://example.com/subscription"
}
In the response body, there is a URL attribute:
Now redirect your customer to this URL immediately. For security purposes, this URL will expire in a few minutes.
After redirecting the customer to this URL, the portal will open and customers can manage their subscriptions and billing details in the portal. customers can return to the app by clicking the Return link on your company’s name or logo within the portal on the left side. They’ll redirect to the return_url you have provided at the time of creating the session or redirect URL set in your portal settings.
Listen to Webhooks
You must have a question, what is this Webhook!!!
It’s just an event, which will fire when a customer does any changes in his/her subscription in the portal, we can listen to this event in our app and make appropriate changes.
For example,
If a customer cancels his/her subscription in the portal, then how we will know about it!!
For it, when customers do any changes in his/her subscription
“customer.subscription.updated” event will be fired and we can listen for this event and, get to know the customer has changed subscription so we need to do appropriate changes in our app also.
Set webhook in your app
In the webhooks.php (in routes folder) file set up a route to handle webhook.
You can use the Laravel Cashier Package (https://laravel.com/docs/8.x/billing)to handle webhooks.
To set up a webhook for your portal navigate to the “Developers > Webhooks” menu you will find the below screen, here I have added a webhook to handle subscription cancel and update events, it will fire when customers update subscription, and you will receive it.
Click on the “Add endpoint” button and the below pop up will open. In Endpoint URL set the route you have created in the webhooks.php file. Select subscription updated and deleted events.
All done.
For more details, you can use stripe customer portal integration
Send Device-to-Device Push Notification using Firebase Cloud MessagingAndroid Development
Send Device-to-Device Push Notification using Firebase Cloud MessagingAndroid Development
Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you deliver messages for free.
It allows you to send push notifications from the Firebase console or from the application server or some trusted server where logic runs.
Step 1:- Create a new Android Studio Project
First, create a new Android Studio project and add the dependencies. First set up Firebase in your project. You can find a good tutorial.
Add Firebase messaging dependency to your app-level.
build.Gradle
dependencies {
implementation 'com.google.firebase:firebase-messaging:19.0.1'
}
Step 2: Create a Firebase Service
The next step is to create Firebase Services:-
MyFirebaseInstanceIDService
and MyFirebaseMessagingService
. first MyFirebaseInstanceIDService
service will handle the device registration process and the second MyFirebaseInstanceIDService
will handle the reception and display of notifications. The services have no visual interface and are used for operations that run in the background. To create a service, right-click and select the Applications folder New -> Service -> Service.
Type in your service name, and click the Finish button. Repeat the same steps for the second service.
AndroidManifest.xml file and update your service declarations under the application tag. Also, add INTERNET
and CLOUD TO DEVICE MESSAGING
permissions so your app can interact with the FCM server.
<!--?xml version="1.0" encoding="utf-8"?-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.exmple.notify">
<uses-permission android:name="android.permission.INTERNET">
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE">
<application android:allowbackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundicon="@mipmap/ic_launcher_round"
android:supportsrtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN">
<category android:name="android.intent.category.LAUNCHER">
</category></action></intent-filter>
</activity>
<service android:name=".MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT">
</action></intent-filter>
</service>
<service android:name=".MyFirebaseMessagingService"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT">
<action android:name="com.google.android.c2dm.intent.RECEIVE">
</action></action></intent-filter>
</service>
</application>
</uses-permission>
</uses-permission>
</manifest>
To handle the device registration process, MyFirebaseInstanceIDService
must increase the FireBaseInstenside service class. Under this service, override the tokenrefresh()
method so that whenever the system decides to refresh the tokens, it will be requested. This usually happens when the user installs/reinstalls the application or when the user clears the application data.
Since you are sending notifications between devices, each user must subscribe to an issue with a different user_id
. This ensures that users receive notifications sent to topics that match their user_id
. Here is the implementation of MyFirebaseInstanceIDSericiclass
.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private final String ADMIN_CHANNEL_ID = "admin_channel";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
final Intent intent = new Intent(this, MainActivity.class);
NotificationManager notificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
int notificationID = new Random().nextInt(3000);
/*
Apps targeting SDK 26 or above (Android O) must implement notification channels and add their notifications to at least one of them.
Therefore, confirm if the version is Oreo or higher, then setup notification channel
*/
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
setupChannels(notificationManager);
}
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.notify_icon);
Uri notificationSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIF CATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, ADMIN_CHANNEL_ID)
.setSmallIcon(R.drawable.notify_icon)
.setLargeIcon(largeIcon)
.setContentTitle(remoteMessage.getData().get("title"))
.setContentText(remoteMessage.getData().get("message"))
.setAutoCancel(true)
.setSound(notificationSoundUri)
.setContentIntent(pendingIntent);
// Set notification color to match your app color template
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
notificationBuilder.setColor(getResources().getColor(R.color.colorPrimaryDark));
}
notificationManager.notify(notificationID, notificationBuilder.build());
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void setupChannels(NotificationManager notificationManager) {
CharSequence adminChannelName = "New notification";
String adminChannelDescription = "Device to device notification ";
NotificationChannel adminChannel;
adminChannel = new NotificationChannel(ADMIN_CHANNEL_ID,
adminChannelName,
NotificationManager.IMPORTANCE_HIGH);
adminChannel.setDescription(adminChannelDescription);
adminChannel.enableLights(true);
adminChannel.setLightColor(Color.RED);
adminChannel.enableVibration(true);
if (notificationManager != null) {
notificationManager.createNotificationChannel(adminChannel);
}
}
}
Step 3: Implement the notification sending logic
This is the most important part of the whole article. This is where you define the content of the instruction and how it will be modeled. However, before you dive into coding, follow these steps to get your server key from the Firebase console.
Navigate to the Cloud Messaging tab, and copy your Server key
Implement the Sending Logic: An FCM server with the following request properties only needs an HTTP post request to send a push notification:
Method Type: POST
URL: https://firebase.google.com/docs/cloud-messaging/http-server-ref
Headers:
Authorization: key="Firebase server key" Content-Type: application/json
Body:
{
"to": "/topics/notification_userId",
"data": {
"title": "Notification title",
"message": "Notification message",
"key1" : "value1",
"key2" : "value2" //additional data you want to pass
}
}
With these concepts in mind, you will first create a JsonObject of Notification body within your activity class. This object budget will contain the subject of the receiver, the title of the notification, the notification message, and the other key/value pair you want to add.
public class MainActivity extends AppCompatActivity {
EditText edtTitle;
EditText edtMessage;
final private String FCM_API = "https://fcm.googleapis.com/fcm/send";
final private String serverKey = "key=" + "Your Firebase server key";
final private String contentType = "application/json";
final String TAG = "NOTIFICATION TAG";
String NOTIFICATION_TITLE;
String NOTIFICATION_MESSAGE;
String TOPIC;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtTitle = findViewById(R.id.edtTitle);
edtMessage = findViewById(R.id.edtMessage);
Button btnSend = findViewById(R.id.btnSend);
btnSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TOPIC = "/topics/userABC"; //topic must match with what the receiver subscribed to
NOTIFICATION_TITLE = edtTitle.getText().toString();
NOTIFICATION_MESSAGE = edtMessage.getText().toString();
JSONObject notification = new JSONObject();
JSONObject notifcationBody = new JSONObject();
try {
notifcationBody.put("title", NOTIFICATION_TITLE);
notifcationBody.put("message", NOTIFICATION_MESSAGE);
notification.put("to", TOPIC);
notification.put("data", notifcationBody);
} catch (JSONException e) {
Log.e(TAG, "onCreate: " + e.getMessage() );
}
sendNotification(notification);
}
});
}
private void sendNotification(JSONObject notification) {
...
}
}
The next step is to request the network server using the library volley, then use the parameters to the root server will request notification on the target device.
public class MainActivity extends AppCompatActivity {
....
private void sendNotification(JSONObject notification) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(FCM_API, notification,
new Response.Listener() {
@Override
public void onResponse(JSONObject response)
{
Log.i(TAG, "onResponse: " + response.toString());
edtTitle.setText("");
edtMessage.setText("");
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Request error", Toast.LENGTH_LONG).show();
Log.i(TAG, "onErrorResponse: Didn't work");
}
}){
@Override
public Map getHeaders() throws AuthFailureError {
Map params = new HashMap<>();
params.put("Authorization", serverKey);
params.put("Content-Type", contentType);
return params;
}
};
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectRequest);
}
}
Finally, add a MySingleton class that will serve as a request queue for instruction requests.
public class MySingleton {
private static MySingleton instance;
private RequestQueue requestQueue;
private Context ctx;
private MySingleton(Context context) {
ctx = context;
requestQueue = getRequestQueue();
}
public static synchronized MySingleton getInstance(Context context) {
if (instance == null) {
instance = new MySingleton(context);
}
return instance;
}
public RequestQueue getRequestQueue() {
if (requestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
requestQueue = Volley.newRequestQueue(ctx.getApplicationContext());
}
return requestQueue;
}
public void addToRequestQueue(Request req) {
getRequestQueue().add(req);
}
}
With it, you're done creating your app. You can start sending push notifications between devices without typing any server-side code. Always make sure that the notification will not be delivered to you if the subject of the recipient is correct. If you do everything right, you will get the same result.
How to build Pagination with Laravel LivewireLaravel
How to build Pagination with Laravel LivewireLaravel
Livewire is a very awesome thing that I have ever seen, the old school developers are still using the jquery and ajax concept to not refresh the page. But forget the jquery and ajax stuff. If you are good at PHP then you can do the same with Laravel Livewire.
Wait what?
Load dynamic data on the page without using ajax? Yes, it is possible with Laravel Livewire. So that is all about laravel livewire, and in this tutorial, we will see how to build laravel pagination with laravel livewire.
Let's start and I hope you have already set up the livewire. Let's say you already have created a component named UsersListing
Now in the users listing, we want to paginate all users and we will list 10 records per page.
How to use pagination with Laravel Livewire
Livewire provides a trait called WithPagination
and you have to add it into your component UsersListing
. Check out the following code:
use Livewire\WithPagination;
use Livewire\Component;
class UsersListing extends Component
{
use WithPagination;
public function render()
{
return view('livewire.users.index', [ 'users' => User::paginate(10), ]);
}
}
And to load pagination you have to add the following code:
@foreach ($users as $user) ...
@endforeach {{ $users->links() }}
That's it, and your laravel pagination now works like charm without page refresh. There is much more about pagination like how to use it with a custom view, how to use it with a custom theme. We will see it in our next tutorial, until then enjoy the code
How to use One Signal in LaravelLaravel
How to use One Signal in LaravelLaravel
The OneSingnal is the market leader in push notification providers. It provides mobile + web push, email & in-app messages, and an easy way to send notifications. OneSignal provides official core PHP APIs but not the Laravel package. We are using OneSignal in many projects and write a bunch of line code in all projects where we needed OneSingnal.
One day I had an idea in my mind why I should not write a Laravel wrapper for OneSignal?. Finally, I wrote the shailesh-ladumor/one-signal Laravel Wrapper for it. Using this package, we can write neat & clean code and just a few lines of code.
OneSignal add this package in his official docs here
You can watch the following video tutorial or follow the article.
This package also works with the previous Laravel version.
Today we are going to see how we can use Laravel OneSignal Wrapper in Laravel. Let's see step by step, how we can do that.
Spet 1: Install Packages
Install shailesh-ladumor/one-signal by the following command,
composer require ladumor/one-signal
Step 2: Publish the config file
Run the following command to publish config file,
php artisan vendor:publish --provider="Ladumor\OneSignal\OneSignalServiceProvider"
Step 3: Add Provider
Add the provider to your config/app.php into the provider section if using a lower version of Laravel,
Ladumor\OneSignal\OneSignalServiceProvider::class
Step 4: Add Facade
Add the Facade to your config/app.php into aliases section,
'OneSignal' => \Ladumor\OneSignal\OneSignal::class
Configure a .env file with following keys
ONE_SIGNAL_APP_ID=XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
ONE_SIGNAL_AUTHORIZE=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX X
ONE_SIGNAL_AUTH_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ONE_SIGNAL_AUTH_KEY
is optional if you do not want to create an app. I hope you are familiar with the One Signal Platform and know how to get APP_ID and AUTHORIZE. If not, you should see the below image for how to get it.
So, we are done. Let's check how to send push notifications.
Check out this code to send a push notification.
use Ladumor\OneSignal\OneSignal;
$fields['include_player_ids'] = ['xxxxxxxx-xxxx-xxx-xxxx-yyyyy']
$message = 'hey!! This is a test push.!' OneSignal::sendPush($fields, $message);