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' => ...

Bad words or Swear words filter Jquery

Bad words or Swear words filter Jquery var blacklist = /\b(4r5e|5h1t|5hit|a55|anal|anus|ar5e|arrse|arse|ass|ass-fucker|asses|assfucker|assfukka|asshole|assholes|asswhole|a_s_s|b!tch|b00bs|b17ch|b1tch|ballbag|balls|ballsack|bastard|beastial|beastiality|bellend|bestial|bestiality|bi+ch|biatch|bitch|bitcher|bitchers|bitches|bitchin|bitching|bloody|blow job|blowjob|blowjobs|boiolas|bollock|bollok|boner|boob|boobs|booobs|boooobs|booooobs|booooooobs|breasts|buceta|bugger|bum|bunny fucker|butt|butthole|buttmuch|buttplug|c0ck|c0cksucker|carpet muncher|cawk|chink|cipa|cl1t|clit|clitoris|clits|cnut|cock|cock-sucker|cockface|cockhead|cockmunch|cockmuncher|cocks|cocksuck|cocksucked|cocksucker|cocksucking|cocksucks|cocksuka|cocksukka|cok|cokmuncher|coksucka|coon|cox|crap|cum|cummer|cumming|cums|cumshot|cunilingus|cunillingus|cunnilingus|cunt|cuntlick|cuntlicker|cuntlicking|cunts|cyalis|cyberfuc|cyberfuck|cyberfucked|cyberfucker|cyberfuckers|cyberfucking|d1ck|damn|dick|dickhead|dildo|dildos|dink|din...