Laravel Posts

post

Last week, we run into a problem for one of the large Gatsby + ReactJS + Laravel projects in hosting which is hosted with Apache Webserver on Amazon AWS EC2. The problem we were facing was, for some reason, when we reload the Gatsby website, it was giving a 404 error page.

If you open a home page and then a normal visit then the website will fully function, but if you reload the page then it gives an error. And we found it happens when we are using Dynamic routing of React Route in Gatsby as per show in Gatsby documentation here.

Also, what we found, if we test the website build with gatsby serve then it works fine. But while using Apache, it behaves differently and we found that this problem has been faced by lots of people over the internet.

So what we came up with is, we used gatsby serve with an apache proxy. Here is how we did it,

Step 1 - Setup Project

As a first step, clone the project on the server and run a command, gatsby build to create a gatsby build.

Step 2 - Setup PM2 for Gatsby Serve

The next step that we need to do is run gatsby serve. But as you know, we can not run this command directly via console, because as you exit from the console, the command will be terminated.

So we will be using pm2 package, a NodeJS utility that is used to run nodejs apps.

For that, we will need to install pm2 globally. Run the following command to install it,

npm install pm2 -g

You can find other installation ways here if you need.

Once the installation has been done, let's run the gatsby serve command via pm2. For that run the following command from the gatsby project folder,

pm2 start gatsby --name my-web-app -- serve

where my-web-app you can replace with the name of your app.

Once, it's running, try to test it, if it's working correctly by opening the URL http://your-ip-address:9000/. Make sure, port 9000 is opened on your server for traffic.

Step 3 - Configure Apache

Once, gatsby serve is working and tested. The next step is to configure apache to proxy all port 80 traffic to port 9000.

For that, edit your apache conf file (or virtual host conf file), and add the following lines (or configure it to something like the following),

<VirtualHost *:80>
        ServerName my-web-app.infyom.com

        ServerAdmin webmaster@infyom.com

        ProxyRequests On
        ProxyPass / http://localhost:9000/
        ProxyPassReverse / http://localhost:9000/

        ErrorLog ${APACHE_LOG_DIR}/my-web-app.infyom.com.error.log
        CustomLog ${APACHE_LOG_DIR}/my-web-app.log combined

        ......
        # any other options below as per your need
        ......
</VirtualHost>

The next step you need to do is restart your apache server by,

sudo service apache2 restart

And then you can just open the URL https://my-web-app.infyom.com and it should work fine.

Bonus

New Deployment

Whenever you deploy a new code, you again need to run gatsby build and then pm2 restart my-web-app. Then only it will take new changes.

Troubleshooting

Sometimes, we found that we need to restart apache as well after the new deployment. so if you run into any trouble, then make sure to restart apache as well and it should solve the problem.

I hope it may help you to resolve your 404 problem.

July 16, 20213 minutesauthorMitul Golakiya
post

Lots of developers have a question How do I set up React in the Laravel application? so, In this article, I show you how to set up a React in Laravel.

We have a video tutorial as well. so, you can watch it or follow this article.

Follow the following steps

I hope you created a Laravel application in your local machine.

You should watch this tutorial first if not and don't know how to create a Laravel application.

Steps 1:

Let's navigate to the resource directory of your laravel application.

Now, create react application using npx create-react-app react-app. also, you can follow an official docs.

Steps 2:

Now, move all the packages from the package,json to package.json which is located in the root directory of the laravel application.

Steps 3:

Run the following command,

npm install

Steps 4:

We need to compile the react application and convert it into js file. so, let's use laravel mix.

Let's open a file webpack.mix.js and put the following code,

 mix.options({
  postCss: [
      require('autoprefixer'),
  ],
});

mix.setPublicPath('public');

mix.webpackConfig({
  resolve: {
      extensions: ['.js', '.vue'],
      alias: {
          '@': __dirname + 'resources'
      }
  },
  output: {
      chunkFilename: 'js/chunks/[name].js',
  },
}).react();

// used to run app using reactjs
mix.js('resources/react-app/src/index.js', 'public/js/app.js').version();
mix.copy('resources/react-app/public', 'public');

Steps 5:

Fire the following command for compile the assets,

npm run dev

Steps 6:

React application compiled successfully and created all files in the public directory. now, we need to include this js file into the laravel root file. I guess we have a fresh laravel project. so, let's add in welcome.balde.php. you can add in any file where you want to load react application.

Include the following line before end the body,

<script type="text/javascript" src="{{ mix('js/app.js') }}"></script>

also, one more thing we should not forget to include a <div id="root"></div> in root file of laravel. I going to put right now into welcome.blade.php

The last step is just to fire the artisan command php artisan serve and open this URL http://127.0.0.1:8000 in the browser.

July 24, 20212 minutesauthorShailesh Ladumor
post

People nowadays are becoming more intelligent, so better to protect our application's content/data from those who are calling themself hackers.
One of the best examples is the data URLs from AWS buckets. it's not a good idea to store sensitive data into a public AWS Bucket, as the URL is accessible by the people.

Of Course, you can store profile avatars and others data to the public bucket's that not contains any confidential information. so that's fine. 
But when it's about confidential information like PAN CARD Details, AADHAR Card Details, Bank Informations we Must Recommend using AWS Protected Bucket.

In this tutorial, we are going to show that how we can prevent that kind of case, Or how we can integrate AWS Protected Bucket in our Laravel Application.
 
The following code will help you to generate a pre-signed AWS URL that will prevent our data, that URL is non guessable and it will expire within some minutes/hours specified by us.

So let's start with some code :

$s3 = \Storage::disk(config('filesystems.s3_protected_disk'));
$client = $s3->getDriver()->getAdapter()->getClient();
$expiry = "+1 minutes";
$command = $client->getCommand('GetObject', [
'Bucket' => \Config::get('filesystems.disks. s3_protected_disk.bucket'),
'Key'    => 'Path to your file',
]);
$request = $client->createPresignedRequest($command, $expiry);
	return (string) $request->getUri();

So here we have created an s3 instance and it's stored on the $s3 variable, we have specified the expiry time as 1 minute so the given URL for data will be expired within a minute.
Also, we have to specify the bucket name and path to our protected file to generate AWS pre-signed URL.

it will return the pre-signed URL and its looks like as the following URL.

             https://pre-signed.s3.au-west-2.amazonaws.com/image.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=xxxxxxxx%2F20180210%2Feu-west-2%2Fs3%2Faws4_request&X-Amz-Date=20210210T171315Z&X-Amz-Expires=60&X-Amz-Signature=xxxxxxxx&X-Amz-SignedHeaders=host

Hope this helps.


July 16, 20212 minutesauthorVishal Ribdiya
post

Generally, we are using a Laravel One Signal package for push notification. if you are planning to use one signal in the mobile application then this package right for you.

Recently, I add a new feature UserDevice. let me explain why I added support for user Device APIs.

We need to create an API to register a device because One Signal sends a push notification using os player id. so, we need to store os_player_id in the backend from the mobile application. So, need to create an API for it.

Now. you can save your time using this package. you can Generate APIs using one artisan command,

php artisan one-signal.userDevice:publish

This command generates the following files,

  • UserDeviceAPIController
  • UserDeviceAPIRepository
  • UserDevice (model)
  • Migration So, everything is ready in minutes and delivered an API on the spot.

Also, do not forget to add the following routes to the api.php file.

use App\Http\Controllers\API\UserDeviceAPIController;

Route::post('user-device/register', [UserDeviceAPIController::class, 'registerDevice']);
Route::get('user-device/{playerId}/update-status', [UserDeviceAPIController::class, 'updateNotificationStatus']);

If you are a good Eye listener then you should watch the video tutorial

July 08, 20211 minuteauthorShailesh Ladumor
post
While developing complex applications, sometimes we have to validate fields and data in a totally customized way, at that time you can use laravel's custom validations rules functionality. 

In this tutorial, we are going to create our own custom validation rule to compare UUID. In our case, I have to check the UUID which is actually a binary string, that exists on DB or not.
Laravel doesn't provide any rule to compare that binary UUID string, so we will create our own validation rule. 

So let's create our custom validation rule::

Generate Custom Validation Class

So here we have created new class with named UuidExists into App\Rules

namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Ramsey\Uuid\Uuid;
class UuidExists implements Rule
{
   
    protected $table;
    protected $column;

    public function __construct($table, $column)
    {
        $this->table = $table;
        $this->column = $column;
    }
    public function passes($attribute, $value)
    {
        $value = Uuid::fromString(strtolower($value))->getBytes();
        return \DB::table($this->table)->where($this->column, $value)->exists();
    }
    public function message()
    {
        return 'The validation error message.';
    }
}


Add Rule to AppService Provider

Add your rule to AppServiceProvider.php into boot() method. here I have to give the named uuid_exists to my custom rule. you can give your own name whatever you want. 

\Validator::extend('uuid_exists', function ($attribute, $value, $parameters, $validator) {
  list($table, $column) = $parameters;
  return (new UuidExists($table, $column))->passes($attribute, $value);
});

How to use custom Rule ?

You can use your custom rule as follows. here we have using required and uuid_exists rule, where we are passing attribute and values to our custom rule, which will be used to passes($attribute, $value) function.

'tenant_id' => ['required', 'uuid_exists:tenant_id,uuid']

Keep connected to us for more interesting posts about Laravel.


January 21, 20211 minuteauthorVishal Ribdiya