Skip to main content

Integrating Repository in Laravel

Create Repositories folder inside App folder => App/Repositories
Now create BaseRepository.php inside the Repositories folder

<?php

namespace App\Repositories;

use Illuminate\Database\Eloquent\Model;

class BaseRepository
{
    /**
     * The Model name.
     *
     * @var \Illuminate\Database\Eloquent\Model;
     */
    protected $model;

    /**
     * Paginate the given query.
     *
     * @param The number of models to return for pagination $n integer
     *
     * @return mixed
     */
    public function getPaginate($n)
    {
        return $this->model->paginate($n);
    }

    /**
     * Create a new model and return the instance.
     *
     * @param array $inputs
     *
     * @return Model instance
     */
    public function store(array $inputs)
    {
        return $this->model->create($inputs);
    }

    /**
     * FindOrFail Model and return the instance.
     *
     * @param int $id
     *
     * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection
     *
     * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
     */
    public function getById($id)
    {
        return $this->model->findOrFail($id);
    }

    /**
     * Update the model in the database.
     *
     * @param $id
     * @param array $inputs
     */
    public function update($idarray $inputs)
    {
        $this->getById($id)->update($inputs);
    }

    /**
     * Delete the model from the database.
     *
     * @param int $id
     *
     * @throws \Exception
     */
    public function destroy($id)
    {
        $this->getById($id)->delete();
    }
}
After this create any repo like user repo and extend BaseRepository
<?php

namespace App\Repositories;

use Illuminate\Database\Eloquent\Model;
use App\User;

use Auth;
use Exception;

use Illuminate\Support\Facades\Log;
use Hash;

class UserRepository extends BaseRepository
{
    
    protected $model;
    function __construct(User $user)
    {
        $this->model = $user;
        //auth()->setDefaultDriver('api');
    }
    public function getUserDetailsById($id)
    {
        try {
            $result = $this->model->where('id'$id)->get();
            if ($result) {
                return $result;
            } else {
                return false;
            }
        } catch (Exception $e) {
            return false;
        }
    }
    
}

after this use this repo in the controller as follows

<?php

namespace App\Http\Controllers\Api;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;
use Auth;
use Illuminate\Support\Facades\Log;
use App\Traits\Devconfig;
use App\Repositories\UserRepository;
class CustomAuthController extends Controller
{
    use Devconfig
    protected $userRepo;
    //protected $guard = '';
    function __construct(UserRepository $userRepo)
    {  
        $this->userRepo = $userRepo;
       $this->middleware('api');
    }
    
    public function helloWorld()
    {
        //die("ok");
        $user = $this->userRepo->getById(1);
        //dd($user);
        Log::debug("entering test method");
        $data['status'] = "fail";
        $data['success_message'] = "OK";
        $data['errors'] = [];
        $data['result'] = $user;
        return response()->json($data$this->successStatusCode);
    }
    
}




Comments

Popular posts from this blog

Laravel Request Validator json response example

 Step 1 :  php artisan make : request  StoreArticleRequest Step 2 : <?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Http\JsonResponse; use Illuminate\Contracts\Validation\Validator; use Illuminate\Http\Exceptions\HttpResponseException; class StoreArticleRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize () { return true ; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules () { return [ 'title' => 'required' ]; } protected function failedValidation (Validator $validator ) { if ($this -> wantsJson () || $this -> ajax ()) { throw new HttpResponseException( response () -> json ([ 'status' => '

AWS EC2, LAMP, Laravel and RDS Installation / setup

This document shows you how to configure AWS environment in Amazon EC2 with RDS Instance. We need to login in to AWS to start the configuration. http://aws.amazon.com Login screen for AWS Management console: First thing we have to select is region. On which region you want to deploy your server. I am going to select Oregon region here for my setup. 1.       click on the launch instance button, 2.       It redirects to following screen. Here we have to search for required operating system or select from list,  here im selecting Ubuntu latest version 4.       After selecting operating system, choose the instance type according to our requirement. Here I need lower configuration so choosing t2.micro type instance.   5.       Click Next button, then you see the below screen. Here we to modify if any settings need to modify Like changing network/subnet. or can skip this by keeping default settings. 6.       Click on next button and Add the st