Categories
Laravel

How to build an API with Laravel 5.8 using Sqlite

This tutorial focuses on setting up REST API in Laravel 5.8 using PHPUnit and SQLITE. If you’re new to Laravel or PHPUnit, Check out the Laravel Getting Started Guide and PHPUnit Documentation for more information.

  1. Install Laravel 5.8

First, let install Laravel 5.8 using the following command (Make sure you have installed composer in your PC). Click on Install Composer If you haven’t installed Composer on your PC.

composer create-project --prefer-dist laravel/laravel restApiApplication
  1. Install & Configure Database

You need to create the database as SQLite and then we need to connect that database to the Laravel project. Create the sqlite file named database.sqlite under database folder as shown below.

database/database.sqlite

Open the .env file inside Laravel project and add the database credentials as below.

.env

DB_CONNECTION=sqlite
DB_DATABASE='project_path'/database/database.sqlite
Code language: JavaScript (javascript)
  1. Create a database model, migration

In this step, we’re going to create a Data model with a few options:

php artisan make:model Data --migration
Code language: CSS (css)

The migration will be created under “database/migrations”. Edit the file with the code below to create Data Table.

‘date’_create_data_table.php

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateDataTable extends Migration
{

public function up()
{
    Schema::create('data', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->text('description');
        $table->timestamps();
    });
}

public function down()
{
    Schema::dropIfExists('data');
}
}
Code language: HTML, XML (xml)

Type the following command to run the migration.

php artisan migrate

Open the generated model in “app/Data.php” Now, Write the schema inside Data.php file.

app/Data.php

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Data extends Model
{
    protected $fillable = ['title','description'];
}
Code language: HTML, XML (xml)
  1. Create DataController

Type the following command at your terminal to create DataController.php file in controllers

php artisan make:controller DataController --resource.
Code language: CSS (css)

app/Http/Controllers/DataController.php

<?php

namespace App\Http\Controllers;

use App\Data;
use Illuminate\Http\Request;

class DataController extends Controller
{
    public function index()
    {
        $data = Data::all();
        return response()->json($data);
    }

    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required',
            'description' => 'required'
        ]);

        $data = Data::create($request->all());

        return response()->json([
            'message' => 'Data Successfully Stored!',
            'data' => $data
        ]);
    }

    public function show(Request $request)
    {
        $data = Data::where('id' , '=' , $request->id)->first();
        return response()->json([
            'message' => 'Fetching Data!',
            'data' => $data
        ]);
    }

    public function update(Request $request, Data $data)
    {
        $request->validate([
            'title'       => 'nullable',
            'description' => 'nullable'
        ]);

        $data->update($request->all());

        return response()->json([	
            'message' => 'Great success! Task updated',
        ]);
    }

    public function destroy(Data $data)
    {
        $data->delete();

        return response()->json([
            'message' => 'Data Successfully deleted!'
        ]);
    }
}
Code language: HTML, XML (xml)

Now, write the routes in routes -> api.php file.

Route::get('/data', 'DataController@index')->name('path.index');
Route::post('/data', 'DataController@store')->name('path.store');
Route::get('/data/{id}', 'DataController@show')->name('path.show');
Route::put('/data/{data}', 'DataController@update')->name('path.update');
Route::delete('/data/{data}', 'DataController@destroy')->name('path.destroy');
Code language: PHP (php)
  1. Creating & Running Tests

Create the test by typing the command below in your terminal.

php artisan make:test DataTest
Code language: CSS (css)

Open phpunit.xml at your project folder and add the following lines about the testing database at the bottom of phpunit.xml. This specifies connecting to a SQLite database for testing that’s stored in memory.

.....
<php>
    <env name="APP_ENV" value="testing"/>
    <env name="BCRYPT_ROUNDS" value="4"/>
    <env name="CACHE_DRIVER" value="array"/>
    <env name="MAIL_DRIVER" value="array"/>
    <env name="QUEUE_CONNECTION" value="sync"/>
    <env name="SESSION_DRIVER" value="array"/>
    <env name="DB_CONNECTION" value="sqlite"/>
    <env name="DB_DATABASE" value=":memory:"/>
</php>
</phpunit>
Code language: HTML, XML (xml)
  1. Create a factory

To simplify creating data, we can use Factories. These Factories are used to insert a few records into the database before running tests. Instead of manually inserting the values of each column to the database.

Type the following command in your terminal to create the factory.

php artisan make:factory DataFactory --model=Data

The factories are located in the database/factories folder. Paste the following code in DataFactory.php

database/factories/DataFactory.php

<?php
use App\Data;
use Faker\Generator as Faker;

$factory->define(Data::class, function (Faker $faker) {
    return [
        'title'       => $faker->sentence(),
        'description' => $faker->text()
    ];
});
Code language: HTML, XML (xml)
  1. Create the Test functions

Inside the test, We need to specify the DatabaseMigrations in tests/Feature folder to set up testing database from the migration files before the first test run.

test/Feature/DataTest.php

<?php

namespace Tests\Feature;

use App\Data;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class DataTest extends TestCase
{
    use RefreshDatabase;


    /** @test */
    public function show_all_data()
    {
        factory(Data::class, 10)->create();

        $response = $this->json('GET', route('path.index'));

        $response->assertStatus(200);

        $response->json();

        /* Uncomment to view Response */
        //print_r($response->json());
    }

    /** @test */
    public function create_data()
    {
        $response = $this->json('POST', route('path.store'), [
            'title'       => 'Dummy title',
            'description' => 'Dummy description'
        ]);

        $response->assertStatus(200);

        $this->assertEquals('Dummy title',$response->json()['data']['title']);

        /* Uncomment to show Response */
        //print_r($response->json());
    }

    /** @test */
    public function show_specific_data()
    {
        $this->json('POST', route('path.store'), [
            'title'       => 'Dummy title',
            'description' => 'Dummy description'
        ]);

        $data = Data::all()->first();

        $response = $this->json('GET', route('path.show',$data->id));

        $response->assertStatus(200);

        $response->json();

        /* Uncomment to show Response */
        //print_r($response->json());
    }

    /** @test */
    public function update_data()
    {
        $this->json('POST', route('path.store'), [
            'title'       => 'Dummy title',
            'description' => 'Dummy description'
        ]);

        $data = Data::all()->first();

        $response = $this->json('PUT', route('path.show',$data->id),['title' => 'Dummy updated title']);

        $response->assertStatus(200);

        $response->json();

        /* Uncomment to show Response */
        //print_r($response->json());
    }

    /** @test */
    public function delete_data()
    {
        $this->json('POST', route('path.store'), [
            'title'       => 'Dummy title',
            'description' => 'Dummy description'
        ]);

        $data = Data::all()->first();

        $response = $this->json('DELETE', route('path.destroy', $data->id));

        $response->assertStatus(200);

        $response->json();

        /* Uncomment to show Response */
        //print_r($response->json());
    }
}
Code language: HTML, XML (xml)

Finally, You are ready to run your Laravel 5.8 API. Type the following command in your terminal to run the tests.

vendor\bin\phpunit

Hope this tutorial helped you! Feel free to drop your opinion at the comment section.

Leave a Reply

Your email address will not be published.