Stori.
Laravel API - Phần 1
5 min read

Laravel API - Phần 1

APILaravelPHP

1. Thiết lập dự án

  • Clone repo
  • git clone https://github.com/bcsdlbnga/website-backend.git
  • Truy cập thư mục
  • cd website-backend
  • Copy file “.env.example” thành file “.env”
  • Chạy dự án bằng docker-compose
  • docker-compose up --build
  • Truy cập từ trình duyệt “127.0.0.1:8000” hoặc “localhost:8000”
  • 2. Code dự án

    2.1. Eloquent

  • Tạo model mới kèm tạo tự động các thành phần liên quan (Model, Controller, DB, …)
  • # Generate a model and a API/V1/PostFactory class...
    php artisan make:model API/V1/Post --factory
    php artisan make:model API/V1/Post -f
     
    # Generate a model and a API/V1/PostSeeder class...
    php artisan make:model API/V1/Post --seed
    php artisan make:model API/V1/Post -s
     
    # Generate a model and a API/V1/PostController class...
    php artisan make:model API/V1/Post --controller
    php artisan make:model API/V1/Post -c
     
    # Generate a model, API/V1/PostController resource class, and form request classes...
    php artisan make:model API/V1/Post --controller --resource --requests
    php artisan make:model API/V1/Post -crR
     
    # Generate a model and a API/V1/PostPolicy class...
    php artisan make:model API/V1/Post --policy
     
    # Generate a model and a migration, factory, seeder, and controller...
    php artisan make:model API/V1/Post -mfsc
     
    # Shortcut to generate a model, migration, factory, seeder, policy, controller, and form requests...
    php artisan make:model API/V1/Post --all
     
    # Generate a pivot model...
    php artisan make:model API/V1/Post --pivot

    Chi tiết: https://laravel.com/docs/9.x/eloquent

    2.2. Database

  • Khai báo các trường dữ liệu cho các model
  • // database\migrations\XXXX_XX_XX_XXXXXX_create_posts_table.php
    public function up()
        {
            Schema::create('posts', function (Blueprint $table) {
                $table->id();
                $table->integer('user_id');
                $table->string('title');
                $table->string('thumbnail'); 
                $table->string('slug');
                $table->text('content');
                $table->tinyText('summary');
                $table->tinyInteger('published');
                $table->dateTime('published_at', $precision = 0);
                $table->timestamps();
            });
        }
    // database\migrations\XXXX_XX_XX_XXXXXX_create_users_table.php
    public function up()
        {
            Schema::create('users', function (Blueprint $table) {
                $table->id();
                $table->string('name');
                $table->string('email')->unique();
                $table->timestamp('email_verified_at')->nullable();
                $table->string('password');
                $table->rememberToken();
                $table->timestamps();
            });
        }
  • Thiết lập quan hệ giữa các bảng dữ liệu (Nếu có khóa ngoại)
  • // app\Models\User.php
    public function posts(){
            return $this->hasMany(Post::class);
        }
    // app\Models\Post.php
    public function user(){
            return $this->belongTo(User::class)
        }

    2.2. Faker

  • Thiết lập dữ liệu ảo bằng faker
  • Faker formatters: https://github.com/fzaninotto/Faker

    // database\factories\PostFactory.php
    public function definition()
        {
            $title = $this->faker->sentence;
            $slug = \Str::slug($title);
            return [
                'user_id' => User::factory(),
                'title' => $title,
                'thumbnail' => $this->faker->imageUrl($width = 640, $height = 480),
                'slug' => $slug,
                'content' => $this->faker->paragraph($nbSentences = 10, $variableNbSentences = false),
                'summary' => $this->faker->paragraph($nbSentences = 2, $variableNbSentences = true),
                'published' => $this->faker->numberBetween($min = 0, $max = 2) ,
                'published_at' => $this->faker->dateTime(),
                'created_at' => $this->faker->dateTime(),
                'updated_at' => $this->faker->dateTime()
            ];
        }
  • Tạo 10 user, mỗi user là chủ nhân của 25 bài viết
  • // database\seeders\DatabaseSeeder.php
    public function run()
        {
             \App\Models\User::factory(10)->hasPosts(25)->create();
        }
  • Chạy câu lệnh migrate để cập nhật thay đổi vào database
  • php artisan migrate:fresh --seed

    2.3. Controller

    I. Tạo controller ResponseController (Mẫu xử lý return) - Không cần model cho controller này

    php artisan make:controller ResponseController

    II. Code mẫu cho ResponseController (Gồm 1 hàm định nghĩa return khi thành công, 1 hàm định nghĩa trả về khi gặp lỗi)

    // app\Http\Controllers\API\V1\ResponseController.php
    class ResponseController extends Controller
    {
        /**
         * success response method.
         *
         * @return \Illuminate\Http\Response
         */
        public function responseSuccess($data, $message)
        {
        	$response = [
                'success' => true,
                'status_code' => 200,
                'message' => $message,
                'results'    => $data,
            ];
            return response()->json($response, 200);
        }
    
    
        /**
         * return error response.
         *
         * @return \Illuminate\Http\Response
         */
        public function responseError($error, $errorMessages = [], $statusCode)
        {
        	$response = [
                'success' => false,
                'status_code' => $statusCode,
                'message' => $error,
                'results' => null
            ];
            if(!empty($errorMessages)){
                $response['data'] = $errorMessages;
            }
            return response()->json($response, $statusCode);
        }
    }

    III. Xử lý PostController

  • index() → Trả về danh sách dữ liệu
  • Trong ví dụ, hàm trả về dữ liệu dưới dạng phân trang, có sử dụng Resource định nghĩa lại dữ liệu trả về đồng thời kết thừa ResponseController để tùy chỉnh phản hồi.

  • create() → Hiển một form để tạo mới dữ liệu (Không cần dùng đến khi code API)
  • store() → Lưu một dữ liệu mới
  • show() → Hiển thị một dữ liệu cụ thể
  • edit() → Hiển thị form để chỉnh sửa một dữ liệu cụ thể
  • update() → Cập nhật một dữ liệu có thay đổi
  • destroy() → Xóa một dữ liệu cụ thể
  • // app\Http\Controllers\API\V1\PostController.php
    
    namespace App\Http\Controllers\API\V1;
    
    use App\Models\Post;
    use App\Http\Requests\StorePostRequest;
    use App\Http\Requests\UpdatePostRequest;
    use App\Http\Resources\PostResource;
    use App\Http\Controllers\API\V1\ResponseController as ResponseController;
    
    class PostController extends ResponseController
    {
        /**
         * Display a listing of the resource.
         *
         * @return \Illuminate\Http\Response
         */
        public function index()
        {
            $posts = Post::paginate();
            $data = PostResource::collection($posts)->resource;
            return $this->responseSuccess($data, 'Posts retrieved successfully.');
        }
    
        /**
         * Show the form for creating a new resource.
         *
         * @return \Illuminate\Http\Response
         */
        public function create()
        {
            //
        }
    
        /**
         * Store a newly created resource in storage.
         *
         * @param  \App\Http\Requests\StorePostRequest  $request
         * @return \Illuminate\Http\Response
         */
        public function store(StorePostRequest $request)
        {
            // 
        }
    
        /**
         * Display the specified resource.
         *
         * @param  \App\Models\Post  $post
         * @return \Illuminate\Http\Response
         */
        public function show(Post $post)
        {
            //
        }
    
        /**
         * Show the form for editing the specified resource.
         *
         * @param  \App\Models\Post  $post
         * @return \Illuminate\Http\Response
         */
        public function edit(Post $post)
        {
            //
        }
    
        /**
         * Update the specified resource in storage.
         *
         * @param  \App\Http\Requests\UpdatePostRequest  $request
         * @param  \App\Models\Post  $post
         * @return \Illuminate\Http\Response
         */
        public function update(UpdatePostRequest $request, Post $post)
        {
            //
        }
    
        /**
         * Remove the specified resource from storage.
         *
         * @param  \App\Models\Post  $post
         * @return \Illuminate\Http\Response
         */
        public function destroy(Post $post)
        {
            //
        }
    }

    Chi tiết: https://laravel.com/docs/9.x/controllers

    2.4. Resource

  • Chuyển đổi dữ liệu từ model thành JSON
  • // app\Http\Resources\PostResource.php
    public function toArray($request)
        {
            return [
                'id' => $this->id,
                'title' => $this->title,
                'content' => $this->detail,
                'slug' => $this->slug,
                'summary' => $this->summary,
                'published_at' => $this->published_at->format('dd/mm/YYYY'),
                'created_at' => $this->created_at->format('dd/mm/YYYY'),
                'updated_at' => $this->updated_at->format('dd/mm/YYYY'),
            ];
        }

    Chi tiết: https://laravel.com/docs/9.x/eloquent-resources

    2.5. Route

  • Khai báo routes
  • // routes\api.php
    Route::group(['prefix'=>'v1', 'namespace' => 'App\Http\Controllers\API\V1'], function(){
        Route::resource('posts', PostController::class);
    });

    Chi tiết: https://laravel.com/docs/9.x/controllers#resource-controllers

  • Truy cập: “localhost:8000/api/v1/posts” để nhận kết quả.
  • Note image

    Tài liệu tham khảo: https://laravel.com/docs/9.x/releases

    Share this article

    Share:
    Read Next Article