In my effort to learn and pass on my knowledge I have developed this tutorial on how to build restful APIs with the Laravel Framework. This is based on a demo/tutorial I gave at the Laravel Meetup Namibia in 2018 at the University of Namibia (UNAM)
## Basic Laravel Restful API
- This application serves to demonstrate the basics of Laravel Restful Api in 10 minutes by creating a todo app
## Step 1 : Create The Todo Model
- The artisan command below creates a model of the name Todo alongside a migration for the database schema
```php
php artisan make:model Todo -m
```
- To solve the Mass Assignment Error
- Add the following field at the top of your Todo model
```php
protected $guarded = [];
```
## Step 2 : Create the controllers
- The artisan command below crerats a controller of the name TodosController and binds it to the Todo model
- The --api parameter adds the methods that a generally used in an api to the created controller
```php
php artisan make:controller TodosController --model=Todo --api
```
- Creates the User Controller
```php
php artisan make:controller UsersController --model=User --api
```
## Step 4 : Create the migration for the Todo model
- Navigate to the created migration and add the following code to the up() method
```php
$table->increments('id');
$table->string('task');
$table->boolean('completed')->default('0');
$table->integer('user_id')->nullable();
$table->timestamps();
```
- Take note that the users migration has been created for your already
- To create your tables, execute the following artisan command to run the migrations
```php
php artisan migrate
```
## Step 5 : Define your relationships
- go to the Todo model and define the relationship that deals with the owner of the task
- we have a one to many relation: one Todo belongs to one User; One user has many Todos
- The code below creates an owner relation in the Todo class
```php
public function owner()
{
return $this->belongsTo(User::class, 'user_id');
}
```
- The code below links a user to his Todos
```php
public function todos()
{
return $this->hasMany(Todo::class);
}
```
## Step 6 : Define Model factories
- paste the following code into the TodoFactory created earlier
```php
$users = \App\User::all()->random(1)->plu …