在CentOS系統中,Laravel路由的定義主要在routes
目錄下的web.php
和api.php
文件中進行。這兩個文件分別用于定義Web應用和API應用的路由。
以下是一些基本的Laravel路由定義示例:
Route::get('/', function () {
return 'Hello, World!';
});
Route::get('/user/{id}', function ($id) {
return 'User ' . $id;
});
Route::get('/user/{id}/posts/{postId}', function ($id, $postId) {
return 'User ' . $id . ' has post ' . $postId;
});
Route::get('/user/{id}', function ($id = 1) {
return 'User ' . $id;
});
Route::get('/user/{id}', function (int $id) {
return 'User ' . $id;
});
Route::post('/user', function () {
return 'This is a POST request';
});
Route::put('/user/{id}', function ($id) {
return 'This is a PUT request for user ' . $id;
});
Route::delete('/user/{id}', function ($id) {
return 'This is a DELETE request for user ' . $id;
});
Route::group(['prefix' => 'admin'], function () {
Route::get('/dashboard', function () {
return 'Admin Dashboard';
});
Route::get('/users', function () {
return 'List of users';
});
});
Route::get('/user/profile', ['as' => 'user.profile', function () {
return 'User Profile';
}]);
// 使用路由名稱生成URL
$url = route('user.profile');
Route::get('/user/{user}', function (App\Models\User $user) {
return 'User ' . $user->name;
});
在定義好路由后,Laravel會根據請求的URL和HTTP方法自動匹配相應的路由,并執行對應的閉包函數或控制器方法。如果找不到匹配的路由,Laravel會返回404錯誤。
請注意,為了使這些示例正常工作,你需要先安裝Laravel框架并配置好Web服務器(如Apache或Nginx)。