RESTful API with CRUD functionality using Laravel 5

by Sam  


You might have heard about RESTful API. By practice, most developers have used third party APIs like that from google and facebook. RESTful API is an application program interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. RESTful API is used in web services development. It allows two software programs to communicate with each another.

This tutorial will help you create your own RESTful API using Laravel 5. On this example, I am using Laravel 5.7.

Let’s get started


1. Install Laravel Framework

Open your terminal and download the Laravel Framework.

composer create-project --prefer-dist laravel/laravel lararestful 

let’s get into the laravel project

cd lararestful

2. Configure your .env file


DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=restfuldb
DB_USERNAME=root
DB_PASSWORD=

Make sure to configure according to your host and database settings. Next, you have to create the database named restfuldb as stated on the .env file above.

3. Create Model and Migration

On this example, we’ll create table for employees.

 php artisan make:model Employee -m 

The code above will automatically create a migration file. Now, navigate to database » migrations » create_employees_table.php and add the fields below.


Schema::create('employees', function (Blueprint $table) {
$table->increments('id');
$table->string('emp_name');
$table->integer('salary');
$table->text('job_description');
$table->timestamps();
});

Next, we have to set the fields as fillable. Go to App»Employee.php.


protected $fillable = ['emp_name', 'salary', 'job_description'];

After configuring the fields above, let’s execute the migration.

php artisan migrate

4. Populate Table with Database Seeding

Since we’re working with RESTful API, we may want to populate the database table with random data. You can do it manually but with Laravel, you can easily do it using seeding.

From your terminal, let’s create EmployeesTableSeeder by typing this command.

php artisan make:seeder EmployeesTableSeeder

The EmployeesTableSeeder file be added automatically into database>>seeds folder. Inside the EmployeesTableSeeder,add the code below inside the run().


public function run()
{
factory(\App\Employee::class, 30)->create();
}

Next, from the same directory, open DatabaseSeeder.php and add the code below.


public function run()
{
$this->call(EmployeesTableSeeder::class);
}

After that, Let’s Make a Factory for our Employee’s seeder.

php artisan make:factory EmployeeFactory

Then, the EmployeeFactory file is added into database>>factories folder. Open the file and let’s modify based on the code below.


$factory->define(App\Employee::class, function (Faker $faker) {
return [
'emp_name' => $faker->name,
'salary' => $faker->numberBetween($min = 5000, $max = 90000),
'job_description'=> $faker->paragraph
];
});

If you notice, I added $faker->numberBetween($min = 5000, $max = 90000) for salary so that it will automatically generate integers from 5000 to 90000.

Finally, let’s insert the data into our employees table.

php artisan db:seed

Check your database and browse if data has been inserted successfully.

6. Make Resources

Let’s make resource for our employees in order to display data in response to the user’s request.

php artisan make:resource EmployeeResource

EmployeeResource file has been added into app\Http\Resources folder.

7. Configure the Routing

Go to routes\api.php and set the routing of our API.


Route::get('employees', 'EmployeeController@index');
Route::get('employee/{id}', 'EmployeeController@show');
Route::post('employee', 'EmployeeController@store');
Route::put('employee/{id}', 'EmployeeController@update');
Route::delete('employee/{id}', 'EmployeeController@destroy');

Let me explain the meaning of routes above.

Route::get(’employees’, ‘EmployeeController@index’); is used to display all employees after the user accesses via http://localhost:8000/api/employees URL

Route::get(’employee/{id}’, ‘EmployeeController@show’); is to get the single employee.

Route::post(’employee’, ‘EmployeeController@store’); if you want to store or create new employee.

Route::put(’employee/{id}’, ‘EmployeeController@update’); if you want to modify the employee based on the ID number.

Route::delete(’employee/{id}’, ‘EmployeeController@destroy’); to delete an employee.

8. Create Resource Controller

This is the final file that we’ll be working on and the “busiest” of them all.

Let’s create our controller for our API.

php artisan make:controller EmployeeController --resource

Customize your controller based on the controller below.


namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Resources\EmployeeResource;
use App\Employee;
use App\Http\Requests;

class EmployeeController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$emp = Employee::all();
return EmployeeResource::collection($emp);
}

/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$emp = new Employee;
$emp->salary = $request->input('salary');
$emp->emp_name = $request->input('emp_name');
$emp->job_description = $request->input('job');
$emp->save();
return new EmployeeResource($emp);
}

/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$article = Employee::find($id); //id comes from route
if( $article ){
return new EmployeeResource($article);
}
return "Employee Not found"; // temporary error
}

/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$emp = Employee::find($id);
$emp->salary = $request->input('salary');
$emp->emp_name = $request->input('emp_name');
$emp->job_description = $request->input('job');
$emp->save();
return new EmployeeResource($emp);
}

/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$emp = Employee::findOrfail($id);
if($emp->delete()){
return new EmployeeResource($emp);
}
return "Error while deleting";
}
}

If you have experienced with Laravel CRUD using resource controller, then the controller above is just easy for you to understand. Else, you can check our previous tutorial on this link: https://www.codespeaker.com/laravel-framework/laravel-5-7-crud-tutorials-with-pagination/.

From our controller, make sure the add the following classes.


use App\Http\Resources\EmployeeResource;
use App\Employee;
use App\Http\Requests;

Congratulations, you’re done!

Start your server.

php artisan serve

Now, let’s test our API. You may test it using your browser but in my case, I use postman software.

GET request, you can send it through this URL:
http://localhost:8000/api/employees

POST request, you can send it through this URL:
http://localhost:8000/api/employee?emp_name=sam&salary=123456&job=webdeveloper

PUT request, you can send it through this URL:
http://localhost:8000/api/employee/1?emp_name=samnew&salary=123456&job=webdeveloper

DELETE request, you can send it through this URL:
http://localhost:8000/api/employee/1


Conclusion

I hope you’re able to create your own RESTful API. Take note, this tutorial is only for CRUD of RESTful api and doesn’t authenticate the user. I will add authentication later on.

If you have any comments or suggestion, please drop it below.

Thank you very much and see you on the next tutorials. 🙂



Leave a Reply

Your email address will not be published. Required fields are marked *


  1. Paul L. says:

    Just to solve a problem for the migration on MySQL.
    after the first ‘php artisan migrate’, i got the error
    ‘sqlstate[42000]: syntax error or access violation: 1071 la clé est trop longue. longueur maximale: 1000 (sql: alter table `users` add unique `users_email_unique`(`email`))’

    To solve it it’s on the file database.php, just change :
    ‘charset’ => ‘utf8mb4’,
    ‘collation’ => ‘utf8mb4_unicode_ci’,

    by

    ‘charset’ => ‘utf8’,
    ‘collation’ => ‘utf8_unicode_ci’

Need of a Website?

Maybe you're planning to build a landing page for your website. You might also have a plan to create a web application. I can offer you with an affordable but with good quality services. Don't hesitate to submit your specifications by clicking the button below.

Get Quote