Cpanel Git: Part 2 - Consuming the Laravel API
Tags: git, github, react, laravel
Published: 2022-12-24 09:43:55

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fndaws5eao98owiv3bgh.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h6ctidlv8bpo1bij66j7.png)


![Creating a new github repository](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kt1ejkxf5pikuim35gv5.png)

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


![Push to existing repo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w9r1ku1z8ch91hxts1tt.png)

Once pushed our repository should look like this


![Laravel Repository example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/czkh2deu21z90l505k4u.png)

### 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uimnkbb6ubc1ool85ro7.png)

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


![VSCode file menu](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lqq5b39vyjzi3aewpmle.png)


![Add to workspace](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k7kgmi0x2gqpyz0gqi2p.png)


![React + Laravel Workspace](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4607n27whlbptrou94og.png)

#### Editing laravel routes
Under the laravel project open `routes/web.php`


![Laravel routes](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/df46m9dggpbyui0piwvi.png)

We will make our route to return the current server time..
So edit the code to this.
```php
Route::get('/', function () {
    return [
        'status'    => true,
        'message'   => null,
        'data'      => now()
    ];
});
```


![Edited Route](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tk8gchxq2utytzmegktl.png)

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

Click on the Terminal menu > New terminal
![New terminal](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bvwn2ki0eur6w0c92gfx.png)

Select the laravel project

![Terminal working directory](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pyly7p4j6c7k97yfnzrx.png)


We will have our terminal

![VSCode terminal](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2kv2m19dk9nn5ihwjslp.png)

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


![Starting laravel server](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pwytirrvb355ztbfquhi.png)

Then open the link in the browser.

![Server response](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2otibpudqamyvg6xnsx5.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r9isehkbze0f8fscon8r.png)

#### 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sh0t9zj9ihuy00r2b3cx.png)

Update the config with this

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


![Updated vite config](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7el56yrjl9v1z3dvg0cw.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yjieddckrm1fv3f94qt3.png)

Start the laravel server inside the terminal with `php artisan serve`


![Artisan serve](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aqz2a6z9k88x7wuhogs9.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/in06v761w1tr0tdjnt9q.png)

Open the react dev server link

![React app](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vrflvk9xb1n82nurgjdh.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/55ukpgq2arac5enjfyqn.png)

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


![Laravel server](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yej4dy41a68be8ljmb93.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fw2zle716soah2uatisz.png)

#### 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.

```jsx
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>
  );
}
```

This is the result..

![Fetch api](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aimeukdv7g8jnvp6c2e2.gif)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1qwvcp0e065eres6tqyj.png)


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.