Laravel Posts

How to use Multi Tenant with Multi Databases Into Any Laravel Application ?

People are quite afraid :), including me :) when it’s about the developing system that works with multi-tenant / multi-database.

In this tutorial, we will implement a multi-tenant system that will create a separate database when the new tenant will create.

Install Package

composer require stancl/tenancy

Then run the following command :

php artisan tenancy:install

Then add the service provider TenancyServiceProvider to your config/app.php file:

/*
 * Application Service Providers...
 */
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
// App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
App\Providers\TenancyServiceProvider::class, // <-- here

Setup Tenant Model

namespace App;

use Stancl\Tenancy\Database\Models\Tenant as BaseTenant;
use Stancl\Tenancy\Contracts\TenantWithDatabase;
use Stancl\Tenancy\Database\Concerns\HasDatabase;
use Stancl\Tenancy\Database\Concerns\HasDomains;

class Tenant extends BaseTenant implements TenantWithDatabase
{
    use HasDatabase, HasDomains;
}

Then, configure the package to use this model in config/tenancy.php:

'tenant_model' => \App\Tenant::class,

Create Migrations For tenant

Create one migration and move that migration file to migrations/tenant. So when we are going to create new tenant this migarations files will run for that new tenant.

You can do the same for seeders. if you want to change the seeder file then you can change it from the config/tenancy.php

Create Actual Tenant

$tenant = Tenant::create([
    'id' => time(),
]);

Result

Now when we run above code it will create new tenant and also create new database with related prefix and given id value.

So it will create following things :

  • New Tenant will be created in main database
  • New tenant database will be created
  • New migrations and seeders will be executed into new tenant database.

Hope that will helps a lot.

June 02, 20221 minuteVishal RibdiyaVishal Ribdiya
How to integrate Authorize Net into Laravel ?

In this tutorial, we are going to see how we can implement the authorized hosted payment gateway by using their UI and components and take payments from users via authorized net using Laravel.

Create HTML form as like below code :

authorize.blade.php

{{ Form::open(array('url' => 'https://test.authorize.net/payment/payment')) }}

Form::hidden('token', '{{$token}}');

Form::submit('Click Me!');

{{ Form::close() }}

You must have to pass $token to form, we will see below how we can generate that token.

AuthorizeController.php

 public function onboard() {

    $token = $this->getAnAcceptPaymentPage();

    return view('authorize', compact('token'));
 }

 public function getAnAcceptPaymentPage()
 {
    $merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
    $merchantAuthentication->setName(config('payments.authorize.login_id'));
    $merchantAuthentication->setTransactionKey(config('payments.authorize.transaction_key'));

    $refId = 'ref' . time();

    $transactionRequestType = new AnetAPI\TransactionRequestType();
    $transactionRequestType->setTransactionType("authCaptureTransaction");
    $transactionRequestType->setAmount("2050"); 

    $setting1 = new AnetAPI\SettingType();
    $setting1->setSettingName("hostedPaymentButtonOptions");
    $setting1->setSettingValue("{\"text\": \"Pay\"}");

    $setting2 = new AnetAPI\SettingType();
    $setting2->setSettingName("hostedPaymentOrderOptions");
    $setting2->setSettingValue("{\"show\": false}");

    $setting3 = new AnetAPI\SettingType();
    $setting3->setSettingName("hostedPaymentReturnOptions");
    $setting3->setSettingValue(
        "{\"url\": \"http://127.0.0.1:8000/authorize-success?refID\".$refID, \"cancelUrl\": \"http://127.0.0.1:8000/authorize-cancel\", \"showReceipt\": true}"
    );

    // Build transaction request
    $request = new AnetAPI\GetHostedPaymentPageRequest();
    $request->setMerchantAuthentication($merchantAuthentication);
    $request->setRefId($refId);
    $request->setTransactionRequest($transactionRequestType);

    $request->addToHostedPaymentSettings($setting1);
    $request->addToHostedPaymentSettings($setting2);
    $request->addToHostedPaymentSettings($setting3);

    $controller = new AnetController\GetHostedPaymentPageController($request);
    $response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::SANDBOX);

    if (($response != null) && ($response->getMessages()->getResultCode() == "Ok")) {

    } else {
        echo "ERROR :  Failed to get hosted payment page token\n";
        $errorMessages = $response->getMessages()->getMessage();
        echo "RESPONSE : " . $errorMessages[0]->getCode() . "  " .$errorMessages[0]->getText() . "\n";
    }
    return $response->getToken();

}

Now create routes into web.php as specified below.

web.php

Route::get('authorize-onboard', [\App\Http\Controllers\AuthorizePaymentController::class, 'onboard'])->name('authorize.init');

Route::get('authorize-success', [\App\Http\Controllers\AuthorizePaymentController::class, 'success']);

How it's going to work ?? (flow)

So initially we will call the route that contains that authorization form and also contains the payment information.

Here we are generating token before, generally, it should be generated from the payment screen.

The token will contains the payment information so while generating it make sure you are passing all the details properly.

Now when you submit the form it will redirect you to the authorized checkout page from where users can do payments and again redirect to the success screen.

Once Payment is done successfully you will be redirected to the success route URL with the RefID which is basically the transaction ID, and you can perform related actions on success action.

Hope it will help.

April 16, 20222 minutesVishal RibdiyaVishal Ribdiya
How to check Laravel logs with UI Interface ?

Debugging the most important thing that developers always need while developing things.

If it's about local environments then we can easily check our logs by putting logs to local but when it's about live environments it's a time-consuming process.

We have to go to the files and open/download those files to local and then we are able to check live logs.

Here we are going to one package that will provide us the UI interface and we can easily check all our logs there.

We can also clear / delete our logs files from there. its better to use daily logs so we can trace logs easily.

Let's see how we can integrate that package to our existing laravel application.

Installation

composer require rap2hpoutre/laravel-log-viewer

Add Service Provider to config/app.php in providers section

Rap2hpoutre\LaravelLogViewer\LaravelLogViewerServiceProvider::class,

Access Logs UI By adding a new route

Route::get('logs', [\Rap2hpoutre\LaravelLogViewer\LogViewerController::class, 'index']);

That's it and you can see all the logs thereby accessing the given route.

That will saves lots of debugging time, hope that will help you :)

February 25, 20221 minuteVishal RibdiyaVishal Ribdiya
How To Setup SSH key in Windows

In this article, I show you how to set up SSH in windows10,

first of all, you have a question what is the ssh key, and why do we need it?

you can watch this video or follow an article.

Let me explain a bit more, An SSH key is a secure access credential used in the Secure Shell protocol. SSH keys use key pairs based on public key infrastructure technology, the gold standard for digital identity authentication and encryption, to provide a secure and scalable method of authentication. as you know all developers use git for pushing, fetching, and pulling their code from GitLab, GitHub, and any other tools.

So, using SSH key you can use git for your repository and get authentication from GitHub or any tool where you add ssh.

When you set up an SSH key, you create a key pair that contains a private key (saved to your local computer) and a public key.

So, Let's Set up SSH for Git on Windows

Step1: Set up your default identity

firs of all open your terminals like gitbash or cmDer.

  • Now, type the command ssh-keygen and enter and command prompts you for a file to save the key in:

$ssh-keygen Generating public/private rsa key pair. Enter file in which to save the key (/c/Users/emmap1/.ssh/id_rsa):

  • Press enter to accept the default key and path,/c/Users/<username>/.ssh/id_rsa. or you can specify the path and then press enter.

  • Enter and re-enter a passphrase when prompted.

  • final out put in your terminal is look likes,

    ssh-keygen 
    Generating public/private rsa key pair.
    Enter file in which to save the key (/c/Users/shailesh/.ssh/id_rsa):
    Created directory '/c/Users/shailesh/.ssh'.
    Enter passphrase (empty for no passphrase):
    Enter the same passphrase again:
    Your identification has been saved in /c/Users/shailesh/.ssh/id_rsa.
    Your public key has been saved in /c/Users/shailesh/.ssh/id_rsa.pub.
    The key fingerprint is: e7:94:d1:a3:02:ee:38:6e:a4:5e:26:a3:a9:f4:95:d4 shailesh@InfyOm-PC
  • Let's navigate to path cd /c/Users/shailesh/.ssh/ and fire ls command for confirming file generated or not.

  • ls command displays two files, one for the public key (for example id_rsa.pub) and one for the private key (for example, id_rsa) if successfully generated.

Step 2: Add SSH in Bitbucket.

  • let's fire command cat id_rsa.pub on the terminal and make sure you stay on the .ssh directory.
  • Now, you can see the key in the terminal. so, copy it and add it to bitbucket. click here for Github to add SSH to your account.

Step 3: Add the SSH key to the ssh-agent.

fire command $eval ssh-agent into the terminal and you get output like Agent pid 9795. 9765 PID may be different in your PC.

Step 4: Check Login in terminal

fire command ssh -T git@bitbucket.org in your terminal and you can get output like

Warning: Permanently added the RSA host key for IP address '104.192.141.1' to the list of known hosts.
authenticated via ssh key.

You can use git to connect to Bitbucket. Shell access is disabled
January 10, 20223 minutesShailesh LadumorShailesh Ladumor
How To Make a Laravel Application PWA In Few Minutes

Recently, I have created a new package for Laravel Community. it's called Laravel PWA. first of all what is PWA? let me explain a bit more about PWA. PWA means progressive web application. PWA provides a facility to install your web application on mobile and desktop. you don't need to write lots of line code in native platform-specific code.

You can create a PWA site in a few minutes using Laravel PWA.

You can watch the video tutorial as well to install this package.

Step 1:

Install the package by the following command,

composer require ladumor/laravel-pwa

Step 2:

Add Service Provide into app.php config file in provider section. You can skip this step if you installed it in Laravel 6 and more.

Ladumor\LaravelPwa\PWAServiceProvider::class,

Step 3:

Add Facade to app.php config file in aliases section. You can skip this step if you installed it in Laravel 6 and more.

'LaravelPwa' => \Ladumor\LaravelPwa\LaravelPwa::class,

Step 4:

I think installation is done and no need to publish all the assets using the following command,

php artisan laravel-pwa:publish

Step 5:

This step is very important. you published all the assets in the previous step. now, you need to link all the assets in your main blade file. for ex app.blade.php

Add the following code in the root blade file in the header section.

<!-- PWA  -->
<meta name="theme-color" content="#6777ef"/>
<link rel="apple-touch-icon" href="{{ asset('logo.PNG') }}">
<link rel="manifest" href="{{ asset('/manifest.json') }}">

Add following code in root blade file before close the body,

<script src="{{ asset('/sw.js') }}"></script>
<script>
    if (!navigator.serviceWorker.controller) {
        navigator.serviceWorker.register("/sw.js").then(function (reg) {
            console.log("Service worker has been registered for scope: " + reg.scope);
        });
    }
</script>

You should watch this tutorial if you want to set it up manually instead of using this package.

October 08, 20213 minutesShailesh LadumorShailesh Ladumor
How to use laravel routes with Javascript / JQuery ?

Generally, we can use laravel routes into its blade files, but what do we have to do when we want to use routes in javascript? is that possible to use laravel routes into javascript?

Yes, now you can use laravel routes into laravel, thanks to Tighten/Ziggi package.

In this tutorial, we will learn how we can use laravel routes into javascript, so let's get started.

Install the package

composer require tightenco/ziggy

Update your main layout file

Add the @routes Blade directive to your main layout (before your application's JavaScript), and the route() helper function will now be available globally!

E.g (app.blade.php)

... ... @routes .. ..

Usage

// routes/web.php

Route::get('users', fn (Request $request) => /* ... */)->name('users.index');

// app.js

route('users.index'); // 'https://url.test/users'

So this is how its works, so simple right :)

You can get more information about this package from here

Kepp connected to us to get the latest laravel information.

January 03, 20223 minutesVishal RibdiyaVishal Ribdiya
How to Setup Swagger in Laravel Application

Generally, we are using a Swagger in Laravel. it will take time if we set up swagger manually. so, In this article, I going to show you very easy steps for setup in Laravel.

You can watch the following video tutorial as well.

Steps 1:

You should download these assets from here. unzip the folder and go to the public directory. you can found the swagger directory in the side public folder. let open the swagger directory and you can see the following files.

  • jquery-2.1.4.min.js
  • style.css
  • swagger-bundle.js
  • swagger.yaml

If are you still confuse then visit this link for files.

now, Copy the swagger directory and put it in your laravel application on the same path.

Steps 2:

We need to load swagger with proper swagger UI. so, let navigate to resources/views on the downloaded source code project.

You can see the swagger directory inside the views directory. copy the swagger directory to your laravel application on the same path. I don't think you need to do anything in this view file. let's go to the next step.

Steps 3:

You need to update this swagger.yaml file. you should update the following details first. and then add APIs documentation in this file. Api document example given here. you can refer it.

info:
  description: LPT APis
  version: 1.0.0
  title: LPT Frontend API's
basePath: /api/

Steps 4:

In this step, you need to create a route for loading swagger docs. so, let's open the web.php file add the following few lines of code.

Route::get('/docs', function () {
    return view('swagger.index');
});

Now, run a command php artisan serve and open http://127.0.0.1:8000/docs or open a virtualHostDomain/docs if you have one.

You should watch this tutorial as well if you using InfyOm Generator

September 06, 20213 minutesShailesh LadumorShailesh Ladumor
How to Implement Browser Push Notification in Laravel
p>In this article, I show you an easy way to set up browser push notifications. fist of all, you have a question what is push notification? let me explain a bit more. Push notification is the fastest way to get up and running with Javascript desktop notifications. Push notifications are messages that can be sent directly to a user's Desktop via browser.

You can watch the following tutorial and you can continue reading this article.

Follow the Steps given here for setup push notification.

Step 1: You can quickly install Push via npm

npm install push.js --save

Step 2: Update webpack.mix.js

Add following code into webpack.mix.js for copy and publish assets like js in the public directory. you can see the example here

mix.copy('node_modules/push.js/bin/push.min.js',
    'public/assets/js/push.min.js');

I hope you know how to use laravel mix. you can watch this video tutorial if you want to know more about the laravel mix.

fire, npm run dev command and publish js.

Step 3: Add assets in blade file

Add script before closing body tag.

<script src="{{ asset('assets/js/push.min.js') }}"></script>

Step 4: Add this code where you want to show a push

// add logo in public dir and use it here
const iconPath = '{{ asset('logo.PNG') }}
 Push.create("Hello Shailesh!",{
       body: "Welcome to the Dashboard.",
       timeout: 5000,
       icon: iconPath
});
December 03, 20213 minutesShailesh LadumorShailesh Ladumor