Adding Endpoints for the Member Entity

Now that we have installed Lumen and set up middleware to handle CORs we are ready to set up our first endpoint. To do this we need a Model for the tennisclub database Member entity. Save the following code to the code \app\Models\Member.php

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class Member extends Model
{

    public function __construct($type = null) 
    {
        parent::__construct();
        $this->setTable("Member");
    }

    public $timestamps=false;

    protected $fillable = [
        'firstname', 'surname', 'membertype', 'dateofbirth'
    ];

    protected $hidden = [
       'userid','created_at', 'updated_at', 'deleted_at'
    ];

}

Lumen does not enable Eloquent ORM by default so before proceeding we need to enable Eloquent so that the model can connect to the database. Open the file bootstrap\app.php and uncomment the line

$app->withEloquent();

as below.

Now add the following code to the file \app\Http\Controllers\MemberController.php

<?php
namespace App\Http\Controllers;
use App\Models\Member as Member;
use Illuminate\Http\Request;

class MemberController extends Controller
{
    public function __construct()
    {
        //
    }
    
    public function showAllMembers()
    {
        $members = Member::all();
        return response()->json($members);
    }
    
    public function showOneMember($id)
    {
        return response()->json(Member::find($id));
    }
   
}

To make these controller functions work we need routes add the following lines to routes\web.php

$router->group(['prefix' => 'api'], function () use ($router) {
    $router->get('members',  ['uses' => 'MemberController@showAllMembers']);
    $router->get('members/{id}', ['uses' => 'MemberController@showOneMember']);
});

We now have now set up two Endpoints for our application. One Endpoint which will show all the members of the tennisclub in json format when we access /members and another which will give us a specific members details when we access /member/id (where id is the specific member's id)

You can access these endpoints via the browser but when we're testing REST Apis we typically use a tool such as curl or postman. Curl was installed with git for windows so it works from the command line.

To test the all members endpoint type the following on the command line

curl -v http://localhost:8000/api/members

Curl uses the GET method by default. The -v adds "verbose" mode so we can see the HTTP headers in the response

The /member/id endpoint can be tested using the following line

In the upcoming posts we'll add PUT, POST and DELETE methods to our endpoints which will enable CRUD like functionality in our application.

Leave a Reply