Laravel authentication api

Tạo table trong database để chứa data laravel transaction (product)

  • Chạy lệnh sau để tạo migration: php artisan make:migration create_products_table
  • Khai báo các field trong file migration mới tạo
public function up() 
   Schema::create('products', function (Blueprint $table) 
     $table->id();
     $table->string('name');
     $table->integer('price');
     $table->timestamps();
   );

Sau khi tạo table, bạn cần phải tạo model Eloquent để ảnh hưởng với table:

  • Chạy lệnh sau để tạo model: php artisan make:model Product
  • Khai báo các field trong file model mới tạo:
<?php
namespace AppModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
class Product extends Model 
   use HasFactory;
   protected $fillable = ['name', 'price'];

Tạo route là việc trọng yếu khi tạo Restful API trong Laravel. Mục đích của tạo route là để nắm tới các path đưa user đến các action trong controller đã tạo ở trên. Để tạo các route api, bạn mở file routes/api.php lên để khái niệm nhé. Khi user thực hiện request đến các route này, phải sở hữu thêm prefix là api, (có thể thay thế bởi trong appProvidersRouteServiceProvider.php) khái niệm route trong api.php nắm tới 2 cách: Cách 1: Khai báo route với 1 method cụ thể (get, post), route (sp), action (index, store). Ví dụ:

use AppHttpControllersProductController;
Route::get('sp', [ProductController::class, 'index']);
Route::post('sp', [ProductController::class, 'store']);

Cách 2: Khai báo route với lệnh Route::resource để dùng chung route đưa cho các method get, post, put, delete dẫn vào các action của controller Route::resource(‘products’, ProductController::class); Lệnh trên tạo ra các route dẫn vào các action như sau:Laravel authentication api

5/5 - (1 bình chọn)

Laravel api - Xây dựng Authentication api

Lê Trương Tấn Lộc (giaodienweb.top/vn)

Có hơn 5 năm thực chiến Python, PHP 7 năm kinh nghiệm trong quản trị web site tư vấn giải pháp Seo top, Digital marketing tối ưu nhất cho doanh nghiệp.
Hiện làm giám đốc kinh doanh tại Siêu Tốc Việt. ping post