Tuesday, 18 June 2024

Create a Laravel 11 API Model

Basic Steps

php artisan make:model
Give it a name
You then have a bunch of options for your model. A good place to start, would be to select.
  • Database Seeder
  • Factory
  • Form Requests
  • Migration
  • Resource Controller
Once run, the system gives you a path list of the files created by this process.
You would then be in a good place to create routes for your API. 

Create your Laravel 11 app as API only

Pre-requisites

I'll assume that you have Laravel set up to use laravel commands.

Make sure you have SQLite installed.

Basic Steps

First, create your application:

laravel new basic-api

Apply the API

php artisan install:api

Delete the resources directory

Delete the file routes/web.php

Delete the line web: __DIR__.'/../routes/web.php', from bootstrap/app.php

Thursday, 13 June 2024

Create a basic API using Laravel 11

This post is specific to Laravel 11, which has a sightly different way of setting up it's API to previous versions.

Pre-requisites

I'll assume that you have Laravel set up to use laravel commands.

Make sure you have SQLite installed.

Basic Steps

Run:

laravel new basic-test

To question 'Would you like to install a starter kit?', select 'No starter kit'.

To question 'Which testing framework do you prefer?',  select 'Pest'.

To question 'Would you like to initialize a Git repository?', select 'yes'.

To question 'Which database will your application use?', select 'SQLite'.

To question 'Would you like to run the default database migrations?', select 'yes'.

To question 'Would you like to create it?', select 'yes'.

Run:

cd basic-test

Run:

php artisan install:api

Within routes/api.php, add the following lines below the 'use' statements:

Route::get('/', function () {

    return response()->json(['message' => 'Hello World']);

});

Run:

php artisan serve

Open a web browser, and add http://127.0.0.1:8000/api/ to the address bar.

You should see some JSON showing the message 'Hello world'.