Api(Resources,Repositories,JWT)
1
Пример реализации Api с использованием Resources,Repositories,JWT
Необходимо добавить пакет tymon/jwt-auth
Необходимо добавить пакет tymon/jwt-auth
app/Http/Controllers/API/V1/LessonController.php
<?php namespace App\Http\Controllers\API\V1; use Illuminate\Http\Request; use App\Http\Controllers\API\V1\AppBaseController;use App\Http\Requests\API\V1\Lesson\CreateUpdateLessonAPIRequest; use App\Http\Resources\Lesson\LessonResource;use App\Reps\LessonRepository; use App\Models\Lesson; class LessonController extends AppBaseController{ private $lessonRepository; public function __construct(LessonRepository $lessonRepo) { $this->lessonRepository = $lessonRepo; } public function index(Request $request) { $lessons = $this->lessonRepository->all( $request->except(['skip', 'limit']), $request->get('skip'), $request->get('limit') ); return $this->sendResponse(LessonResource::collection($lessons), 'Lessons retrieved successfully'); } public function store(CreateUpdateLessonAPIRequest $request) { $input = $request->all(); $lesson = $this->lessonRepository->create($input); return $this->sendResponse(LessonResource::make($lesson), 'Lesson saved successfully'); } public function show($id) { $lesson = $this->lessonRepository->find($id); if (empty($lesson)) { return $this->sendError('Lesson not found'); } return $this->sendResponse(LessonResource::make($lesson), 'Lesson retrieved successfully'); } public function update($id, CreateUpdateLessonAPIRequest $request) { $input = $request->all(); $lesson = $this->lessonRepository->find($id); if (empty($lesson)) { return $this->sendError('Lesson not found'); } $lesson = $this->lessonRepository->update($input, $id); return $this->sendResponse(LessonResource::make($lesson), 'Lesson updated successfully'); } public function destroy($id) { $lesson = $this->lessonRepository->find($id); if (empty($lesson)) { return $this->sendError('Lesson not found'); } $lesson->delete(); return $this->sendSuccess('Lesson deleted successfully'); }}
app/Http/Controllers/API/V1/AppBaseController.php
<?php namespace App\Http\Controllers\API\V1; use App\Http\Controllers\Controller; use App\Utilities\ResponseUtilities; class AppBaseController extends Controller{ public function sendResponse($result, $message) { return response()->json(ResponseUtilities::makeResponse($message, $result)); } public function sendError($error, $code = 404) { return response()->json(ResponseUtilities::makeError($error), $code); } public function sendSuccess($message) { return response()->json([ 'success' => true, 'message' => $message ], 200); } public function respondWithToken($token) { return response()->json([ 'success' => true, 'access_token' => $token, 'token_type' => 'bearer', 'expires_in' => auth()->guard()->factory()->getTTL() * 60 ]); }}
app/Http/Controllers/API/V1/Lesson/CreateUpdateLessonAPIRequest.php
<?php namespace App\Http\Requests\API\V1\Lesson; use Illuminate\Foundation\Http\FormRequest; class CreateUpdateLessonAPIRequest 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 [ 'name' => 'required|string|min:1', 'description' => 'required|string|min:1', 'course_id' => 'required|exists:courses,id', 'status' => 'in:active,archived,deleted' ]; }}
app/Http/Resources/Lesson/LessonCollection.php
<?php namespace App\Http\Resources\Lesson; use Illuminate\Http\Resources\Json\ResourceCollection; class LessonCollection extends ResourceCollection{ public $collects = 'App\Http\Resources\Lesson\LessonResource'; /** * Transform the resource collection into an array. * * @param \Illuminate\Http\Request $request * @return array */ public function toArray($request) { return [ 'data' => $this->collection, ]; }}
app/Http/Resources/Lesson/LessonResource.php
<?php namespace App\Http\Resources\Lesson; use Illuminate\Http\Resources\Json\JsonResource; class LessonResource extends JsonResource{ public $preserveKeys = true; /** * Transform the resource into an array. * * @param \Illuminate\Http\Request $request * @return array */ public function toArray($request) { return [ 'id' => $this->id, 'name' => $this->name, 'description' => $this->description, 'course_id' => $this->course_id, 'video_id' => $this->video_id, 'status' => $this->status, ]; }}
app/Models/User.php
<?php namespace App\Models; use Tymon\JWTAuth\Contracts\JWTSubject; use Illuminate\Notifications\Notifiable;use Illuminate\Contracts\Auth\MustVerifyEmail;use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable implements JWTSubject{ use Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'fist_name', 'last_name', 'phone', 'email', 'password', ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'email_verified_at' => 'datetime', ]; /** * Get the identifier that will be stored in the subject claim of the JWT. * * @return mixed */ public function getJWTIdentifier() { return $this->getKey(); } /** * Return a key value array, containing any custom claims to be added to the JWT. * * @return array */ public function getJWTCustomClaims() { return []; }}
app/Reps/BaseRepository.php
<?phpnamespace App\Reps; use Illuminate\Container\Container as Application;use Illuminate\Database\Eloquent\Model; abstract class BaseRepository{ protected $model; protected $app; public function __construct(Application $app) { $this->app = $app; $this->makeModel(); } abstract public function getFieldsSearchable(); abstract public function model(); public function makeModel() { $model = $this->app->make($this->model()); if (!$model instanceof Model) { throw new \Exception("Class {$this->model()} must be an instance of Illuminate\\Database\\Eloquent\\Model"); } return $this->model = $model; } public function paginate($perPage, $columns = ['*']) { $query = $this->allQuery(); return $query->paginate($perPage, $columns); } public function allQuery($search = [], $skip = null, $limit = null) { $query = $this->model->newQuery(); if (count($search)) { foreach($search as $key => $value) { if (in_array($key, $this->getFieldsSearchable())) { $query->where($key, $value); } } } if (!is_null($skip)) { $query->skip($skip); } if (!is_null($limit)) { $query->limit($limit); } return $query; } public function all($search = [], $skip = null, $limit = null, $columns = ['*']) { $query = $this->allQuery($search, $skip, $limit); return $query->get($columns); } public function create($input) { $model = $this->model->newInstance($input); $model->save(); return $model; } public function find($id, $columns = ['*']) { $query = $this->model->newQuery(); return $query->find($id, $columns); } public function update($input, $id) { $query = $this->model->newQuery(); $model = $query->findOrFail($id); $model->fill($input); $model->save(); return $model; } public function delete($id) { $query = $this->model->newQuery(); $model = $query->findOrFail($id); return $model->delete(); }}
app/Reps/LessonRepository.php
<?php namespace App\Reps; use App\Models\Lesson;use App\Reps\BaseRepository; /** * Class LessonRepository * @package App\Reps * @version April 23, 2020, 12:12 pm UTC*/ class LessonRepository extends BaseRepository{ /** * @var array */ protected $fieldSearchable = [ 'name', 'description', 'course_id', 'video_id', 'status' ]; /** * Return searchable fields * * @return array */ public function getFieldsSearchable() { return $this->fieldSearchable; } /** * Configure the Model **/ public function model() { return Lesson::class; }}
app/Utilities/ResponseUtilities.php
<?php namespace App\Utilities; class ResponseUtilities{ /** * @param string $message * @param mixed $data * * @return array */ public static function makeResponse($message, $data) { return [ 'success' => true, 'data' => $data, 'message' => $message, ]; } /** * @param string $message * @param array $data * * @return array */ public static function makeError($message, array $data = []) { $res = [ 'success' => false, 'message' => $message, ]; if (!empty($data)) { $res['data'] = $data; } return $res; }}
composer.json
{ "require": { "tymon/jwt-auth": "^1.0" }}