Create Repositories folder inside App folder => App/Repositories
Now create BaseRepository.php inside the Repositories folder
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($id, array $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();
}
}
<?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
Post a Comment