laravel專案筆記

漫漫长路</>發表於2024-03-26

要搭建好php環境和composer環境

1.新建專案

composer create-project --prefer-dist laravel/laravel <專案名>

2.資料庫遷移

php artisan migrate

3.建立一個Job模型

php artisan make:model Job -mf

4.建立一個Job控制器

php artisan make:controller JobController --resource

5.模型弄好後重新整理建表

php artisan migrate:refresh --send

6.安裝 Laravel Debugbar

composer require barryvdh/laravel-debugbar --dev

7. 安裝tailwind,如果不想一直執行npm run dev,可以直接npm run build。mix是比較舊的模式了,不太受歡迎

8. 安裝佈局模板 Layouts Using Components

php artisan make:component Layout --view

9.瞭解babel

api

1. 建立api控制器的指令

php artisan make:controller Api/EventController --api

2.建立模型表的

php artisan make:model Event -m

Models下的

class Event extends Model
{
    use HasFactory;
    public function user():BelongsTo
    {
        return $this->belongsTo(User::class);
    }
    public function attendees():HasMany
    {
        return $this->hasMany(Attendee::class);
    }
}

database下的2024_03_25_145533_create_events_table.php

   public function up()
    {
        Schema::create('events', function (Blueprint $table) {
            $table->id();
            $table->foreignIdFor(\App\Models\User::class);
            $table->string('name');
            $table->text('description')->nullable();
            $table->dateTime('start_time');
            $table->dateTime('end_time');
            $table->timestamps();
        });
    }

3. 事件模型(生成資料)

php artisan make:factory EventFactory --model=Event

php artisan make:seeder EventSeeder

database資料夾下

EventFactory.php檔名要配置表的欄位那些
 public function definition()
    {
        return [
            'name'=>fake()->unique()->sentence(3),
            'description'=>fake()->text,
            'start_time'=>fake()->dateTimeBetween('now','+1 month'),
            'end_time'=>fake()->dateTimeBetween('+1 month','+2 month'),
        ];
    }

EventSeeder.php 跑起來
 public function run()
    {
        $users=User::all();
        for($i=0;$i<200;$i++){
            $user=$users->random();
            \App\Models\Event::factory()->create([
                'user_id'=>$user->id
            ]);
        }
    }



填充資料庫

php artisan migrate:refresh --seed

4. 在控制器中返回資料

   public function index()
    {
        return \App\Models\Event::all();
    }

5.路由api.php

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Route::apiResource('events',\App\Http\Controllers\Api\EventController::class);
Route::apiResource('events.attendees',\App\Http\Controllers\Api\AttendeeController::class)
    ->scoped(['attendee'=>'event']);

6.請求獲取資料

http://127.0.0.1:8000/api/events






相關文章