How to make a REST API first web application in Laravel How to make a REST API first web application in Laravel php php

How to make a REST API first web application in Laravel


You should utilize the Repository / Gateway design pattern: please see the answers here.

For example, when dealing with the User model, first create a User Repository. The only responsibility of the user repository is to communicate with the database (performing CRUD operations). This User Repository extends a common base repository and implements an interface containing all methods you require:

class EloquentUserRepository extends BaseRepository implements UserRepository{    public function __construct(User $user) {        $this->user = $user;    }    public function all() {        return $this->user->all();    }    public function get($id){}    public function create(array $data){}    public function update(array $data){}    public function delete($id){}    // Any other methods you need go here (getRecent, deleteWhere, etc)}

Then, create a service provider, which binds your user repository interface to your eloquent user repository. Whenever you require the user repository (by resolving it through the IoC container or injecting the dependency in the constructor), Laravel automatically gives you an instance of the Eloquent user repository you just created. This is so that, if you change ORMs to something other than eloquent, you can simply change this service provider and no other changes to your codebase are required:

use Illuminate\Support\ServiceProvider;class RepositoryServiceProvider extends ServiceProvider {    public function register() {        $this->app->bind(            'lib\Repositories\UserRepository',        // Assuming you used these            'lib\Repositories\EloquentUserRepository' // namespaces        );    }}

Next, create a User Gateway, who's purpose is to talk to any number of repositories and perform any business logic of your application:

use lib\Repositories\UserRepository;class UserGateway {    protected $userRepository;    public function __construct(UserRepository $userRepository) {        $this->userRepository = $userRepository;    }        public function createUser(array $input)        {            // perform any sort of validation first            return $this->userRepository->create($input);        }}

Finally, create your User web controller. This controller talks to your User Gateway:

class UserController extends BaseController {    public function __construct(UserGatway $userGateway)    {        $this->userGateway = $userGateway;    }    public function create()    {        $user = $this->userGateway->createUser(Input::all());    }}

By structuring the design of your application in this way, you get several benefits: you achieve a very clear separation of concerns, since your application will be adhering to the Single Responsibility Principle (by separating your business logic from your database logic) . This enables you to perform unit and integration testing in a much easier manner, makes your controllers as slim as possible, as well as allowing you to easily swap out Eloquent for any other database if you desire in the future.

For example, if changing from Eloquent to Mongo, the only things you need to change are the service provider binding as well as creating a MongoUserRepository which implements the UserRepository interface. This is because the repository is the only thing talking to your database - it has no knowledge of anything else. Therefore, the new MongoUserRepository might look something like:

class MongoUserRepository extends BaseRepository implements UserRepository{    public function __construct(MongoUser $user) {        $this->user = $user;    }    public function all() {        // Retrieve all users from the mongo db    }    ...}

And the service provider will now bind the UserRepository interface to the new MongoUserRepository:

 $this->app->bind(        'lib\Repositories\UserRepository',               'lib\Repositories\MongoUserRepository');

Throughout all your gateways you have been referencing the UserRepository, so by making this change you're essentially telling Laravel to use the new MongoUserRepository instead of the older Eloquent one. No other changes are required.


You should be use Repository for this design.

Example -

//UserRepository Classclass UserRepository {    public function getById($id)    {      return User::find($id);    }}// WebUser Controllerclass WebUserController extends BaseController {    protected $user;    public function __construct(UserRepository $user)    {        $this->user = $user;    }    public function show($id)    {        return View::make('user.view')->with('data', $this->user->getById($id));    }}// APIUser Controllerclass UserController extends BaseController {    protected $user;    public function __construct(UserRepository $user)    {        $this->user = $user;    }    public function show($id)    {        $data =>$this->user->getById($id);        return Response::json(array('success'=>true,'user'= $data->toArray()));    }}