laravel 是一款 php 框架,用于輕松構(gòu)建 Web 應(yīng)用程序。它提供一系列強大的功能,包括:安裝: 使用 composer 全局安裝 Laravel CLI,并在項目目錄中創(chuàng)建應(yīng)用程序。路由: 在 routes/web.php 中定義 URL 和處理函數(shù)之間的關(guān)系。視圖: 在 resources/views 中創(chuàng)建視圖以呈現(xiàn)應(yīng)用程序的界面。數(shù)據(jù)庫集成: 提供與 mysql 等數(shù)據(jù)庫的開箱即用集成,并使用遷移來創(chuàng)建和修改表。模型和控制器: 模型表示數(shù)據(jù)庫實體,控制器處理 http 請求。
Laravel 入門實例
什么是 Laravel?
Laravel 是一個為快速、輕松地構(gòu)建 Web 應(yīng)用程序而設(shè)計的 PHP 框架。它提供了一系列強大的功能,可讓開發(fā)者專注于業(yè)務(wù)邏輯,無需擔(dān)心底層基礎(chǔ)設(shè)施。
安裝 Laravel
- 安裝 Composer(PHP 包管理器)。
- 使用 Composer 全局安裝 Laravel CLI:composer global require laravel/installer。
- 在項目目錄中運行 laravel new my-app 創(chuàng)建新應(yīng)用程序。
創(chuàng)建路由
路由定義 Web 應(yīng)用程序中 URL 和處理函數(shù)之間的關(guān)系。在 routes/web.php 中創(chuàng)建路由:
Route::get('/welcome', function () { return view('welcome'); });
編寫視圖
視圖包含 html 和 PHP 代碼,用于呈現(xiàn)應(yīng)用程序的界面。在 resources/views/welcome.blade.php 中創(chuàng)建一個視圖:
<!DOCTYPE html> <html> <head> <title>Welcome</title> </head> <body> <h1>歡迎來到 Laravel!</h1> </body> </html>
運行應(yīng)用程序
在項目目錄中運行 php artisan serve 啟動開發(fā)服務(wù)器。然后在瀏覽器中訪問 http://localhost:8000/welcome 即可查看視圖。
數(shù)據(jù)庫集成
Laravel 提供與 MySQL、Postgres 和其他數(shù)據(jù)庫的開箱即用的集成。使用遷移來創(chuàng)建和修改數(shù)據(jù)庫表:
php artisan make:migration create_users_table php artisan migrate
模型和控制器
模型表示數(shù)據(jù)庫中的實體,控制器處理 HTTP 請求。
在 app/Models/User.php 中創(chuàng)建模型:
class User extends Model { // ... }
在 app/Http/Controllers/UserController.php 中創(chuàng)建控制器:
class UserController extends Controller { public function index() { $users = User::all(); return view('users.index', ['users' => $users]); } }