• Calculating...
  • 5 years ago
  • 7.5K Views
  • Archived This is an Archived post.
    The content within this may not be used or replaced with newer versions.

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

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');
}
}
 

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'];
}
 
  1. Create DataController

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

php artisan make:controller DataController --resource.
 

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!'
        ]);
    }
}
 

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');
 
  1. Creating & Running Tests

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

php artisan make:test DataTest
 

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>
 
  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()
    ];
});
 
  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());
    }
}
 

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.

 

Share:

Related Post

CRUD Operations In Laravel 8

This tutorial is created to illustrate the basic CRUD (Create , Read, Update, Delete) operation using SQL with Laravel 8. Laravel is one of the fastest-growing frameworks for PHP.

  • 3 years ago

Scheduling Tasks with Cron Job in Laravel 5.8

Cron Job is used to schedule tasks that will be executed every so often. Crontab is a file that contains a list of scripts, By editing the Crontab, You can run the scripts periodically.

  • 5 years ago

Connecting Multiple Databases in Laravel 5.8

This tutorial is created to implement multiple database connections using mysql. Let’s see how to configure multiple database connections in Laravel 5.8.

  • 5 years ago

Integrating Google ReCaptcha in Laravel 5.8

reCAPTCHA is a free service from Google. It’s a CAPTCHA-like system designed to recognize that the user is human and, at the same time, assist in the digitization of books. It helps to protects your w

  • 5 years ago

Clearing Route, View, Config Cache in Laravel 5.8

Sometimes you may face an issue that the changes to the Laravel Project may not update on the web. This occures when the application is served by the cache. In this tutorial, You’ll learn to Clear App

  • 5 years ago