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

Laravel authentication api

Tạo table trong database để chứa dữ liệu đã 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();
     thôi );

Sau khi tạo table, bạn cần tạo model Eloquent để liên quan 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'];
  cũ 

Tạo route là việc quan trọng khi tạo Restful API trong Laravel. Mục đích của tạo route là để sở hữu cả 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 để định nghĩa nhé. Khi user làm request đến các route này, phải nắm tới thêm prefix là api, (có thể chuyển hướng trong appProvidersRouteServiceProvider.php) định nghĩa route trong api.php nắm tới 2 cách: Cách 1: Khai báo route với 1 method chi tiết (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 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 giống như sau:Laravel authentication api

Laravel api - Xây dựng Authentication api

[sale_data type="name"] ([sale_data type="domain"])

[wpts_spin]{Với hơn|Với|Có hơn|Trải qua} {3|4|5|6} năm {kinh nghiệm|thực chiến} {Python, PHP|CSS, JS|Wordpress, asp.net|Laravel|Drupal} {5|6|7|8} năm {kinh nghiệm|thực chiến} trong {quản trị website|quản lý website|quản trị web site|quản lý web site} tư vấn giải pháp {SEO từ khóa|Seo top|Seo google|đẩy top}, {Marketing|Digital marketing|Kinh doanh online} tối ưu nhất cho {doanh nghiệp|công ty|tập đoàn quốc tế}.
Hiện {đang là|là|làm|giữ chức vụ} {trưởng phòng|leader|giám đốc|quản lý} kinh doanh tại Siêu Tốc Việt.[/wpts_spin]


Gọi điện ngay