DEV Community

Sadiq Salau
Sadiq Salau

Posted on • Updated on

Cpanel Git: Part 2 - Consuming the Laravel API

This is the second part of my post which will focus on connecting the react app with laravel.

The first thing to do is to scaffold a new laravel project. Ensure you've installed composer.

Scaffolding a new laravel app

We are going to use composer to create our new laravel app.

composer create-project laravel/laravel example-laravel-app

Scaffolded laravel app

Once scaffolded navigate into your laravel app and initiate a git repository.

cd example-laravel-app
git init
git add .
git commit -m "Initial Project"

Once again head over to github and create a new repository and push to it.. For this tutorial it will be called cpanel-laravel-example

Creating a new github repository

Creating a new github repository

We are going to push to our exisiting repository, so we will follow the github commands.

Push to existing repo

Once pushed our repository should look like this

Laravel Repository example

Connecting our react app to the laravel app on localhost

Now we are working with two repositories, you can add both of them under a workspace if you are using VSCode.

Let's open the first one: example-react-app

React App VSCode

Open the file menu and add the example-laravel-app to workspace.

VSCode file menu

Add to workspace

React + Laravel Workspace

Editing laravel routes

Under the laravel project open routes/web.php

Laravel routes

We will make our route to return the current server time..
So edit the code to this.

Route::get('/', function () {
    return [
        'status'    => true,
        'message'   => null,
        'data'      => now()
    ];
});
Enter fullscreen mode Exit fullscreen mode

Edited Route

Once edited we will launch our laravel server. Let's open a terminal.

Click on the Terminal menu > New terminal
New terminal

Select the laravel project

Terminal working directory

We will have our terminal

VSCode terminal

Let's start the server by running the command php artisan serve

Starting laravel server

Then open the link in the browser.

Server response

We got exactly what we are expecting.
Now let's commit and push our changes.
git add .
git commit -m "Updated route"
git push

Updated route

Proxying react dev server request

Open vite.config.js under the example-react-app and add the server option. Read more at https://vitejs.dev/config/server-options.html

Vite config

Update the config with this

export default defineConfig({
  server: {
    proxy: {
      "^/(api|storage)/.*": {
        target: "http://localhost:8000",
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ""),
      },
    },
  },
  plugins: [react()],
});
Enter fullscreen mode Exit fullscreen mode

Updated vite config

We are going to proxy every request that begins with /api or /storage to the laravel server.

Also we added the changeOrigin option to avoid CORS error https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

We also need to rewrite the request path by removing /api/ from the beginning because a request to http://localhost:8000/api/ doesn't exist as we haven't defined any route to /api in our laravel application so it will be converted to http://localhost:8000/.

To test this let's open two terminals using the instruction earlier.
One for the react app and one for the laravel project.

Two terminals

Start the laravel server inside the terminal with php artisan serve

Artisan serve

Start the react dev server the way you scaffolded it, in my case I used pnpm so it will be pnpm dev. Yours could be yarn dev

React dev server

Open the react dev server link

React app

Add /api/ at the end. Note the trailing / at the end of api, it's required because that's how we defined our proxy.

API proxy

You will get the same response as you would if accessing the laravel server directly

Laravel server

With that done let's commit our changes under the react app.
git add .
git commit -m "Enabled proxy for /api and /storage"
git push

Commiting changes

Fetching data

A real-world example will be to fetch data from the laravel server in our react app.
So let's edit src/App.jsx in our react app and update it will an effect that fetches the time.

function App() {
  const [loading, setLoading] = useState(true);
  const [time, setTime] = useState(null);

  useEffect(() => {
    fetch("/api/")
      .then((response) => response.json())
      .then((data) => {
        setTime(data.data);
        setLoading(false);
      });
  }, []);

  return (
    <div className="App">
      <div>
        <a href="https://vitejs.dev" target="_blank">
          <img src="/vite.svg" className="logo" alt="Vite logo" />
        </a>
        <a href="https://reactjs.org" target="_blank">
          <img src={reactLogo} className="logo react" alt="React logo" />
        </a>
      </div>
      <h1>Vite + React</h1>
      <div className="card">{loading ? "Loading" : time}</div>
      <p className="read-the-docs">
        Click on the Vite and React logos to learn more
      </p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

This is the result..

Fetch api

Now let's commit and push our changes in the react app.

git add .
git commit -m "Fetch and show time"
git push

Pushing changes

A working example of the laravel project can be found at: https://github.com/sadiqsalau/cpanel-laravel-example

With all that done, the next part of this post explains how to deploy the laravel application to our cpanel shared hosting.

Top comments (0)