Laravel 新手場的紀錄
windows 10 家用版 可能裝不起來 Docker
想挑戰可以參考 搭建 Laravel Sail 开发环境 - Windows
使用 Sail 安裝環境
- 下載 Docker
docker ps
- 下載一個 image
curl -s https://laravel.build/example-app | bash
./vendor/bin/sail up
route, controller
- 介紹路由
- 介紹控制器
請求與路由
- Laravel 的請求入口點是
index.php
,在經過一連串的啟動後 request 會分派到路由檔案 eg.routes/web.php
- 路由檔案會將請求分派給控制器
public/index.php
<?php
define('LARAVEL_START', microtime(true));
/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader for
| our application. We just need to utilize it! We'll simply require it
| into the script here so that we don't have to worry about manual
| loading any of our classes later on. It feels great to relax.
|
*/
require __DIR__.'/../vendor/autoload.php';
/*
|--------------------------------------------------------------------------
| Turn On The Lights
|--------------------------------------------------------------------------
|
| We need to illuminate PHP development, so let us turn on the lights.
| This bootstraps the framework and gets it ready for use, then it
| will load up this application so that we can run it and send
| the responses back to the browser and delight our users.
|
*/
$app = require_once __DIR__.'/../bootstrap/app.php';
/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can handle the incoming request
| through the kernel, and send the associated response back to
| the client's browser allowing them to enjoy the creative
| and wonderful application we have prepared for them.
|
*/
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
$response = $kernel->handle(
$request = Illuminate\Http\Request::capture()
);
$response->send();
$kernel->terminate($request, $response);
撰寫路由
開啟 routes/web.php 開始撰寫第一個路由
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcom');
});
語法是一個配對的字串與一個 callback function。
預設範例是讓 /
回傳一個叫做 welcom 的 view(有關畫面,即 laravel blade 會在下一次介紹 )。
控制器
既然是動態網站,通常會有一些邏輯要處理,通常不會將邏輯直接寫在路由檔案裡,而是抽到控制器。(參考:MVC 架構)
可以透過 artisan 指令建立 controller
php artisan make:controller HelloController
這樣就會在 app/Http/Controllers/ 底下建立一個 HelloController.php
開啟 HelloController.php
<?php
namespace App\Http\Controllers\;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class HelloController extends Controller
{
public function home(): string
{
return 'Hello Controller';
}
}
在這個 controller 裡面寫下一個 home function
回到路由檔案寫下,我們希望將 /home 匹配到我們建立的 HomeController 裡面的 home function
Route::get('/home', 'HomeController@home');
在 Laravel 8 之前使用字串匹配,但目前建議使用陣列
Route::get('/home', HomeController@home);