Skip to content

Commit 0a79741

Browse files
author
qiang.sun
committed
路由进阶使用
1 parent c3705e3 commit 0a79741

File tree

3 files changed

+23
-3
lines changed

3 files changed

+23
-3
lines changed

app/Models/Task.php

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,7 @@
66

77
class Task extends Model
88
{
9-
//
9+
public function getRouteKeyName() {
10+
return 'name'; // 以任务名称作为路由模型绑定查询字段
11+
}
1012
}

app/Providers/RouteServiceProvider.php

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace App\Providers;
44

5+
use App\Models\Task;
56
use Illuminate\Support\Facades\Route;
67
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
78

@@ -23,7 +24,8 @@ class RouteServiceProvider extends ServiceProvider
2324
*/
2425
public function boot()
2526
{
26-
//
27+
// 显式路由模型绑定
28+
Route::model('task_model', Task::class);
2729

2830
parent::boot();
2931
}

routes/web.php

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,4 +95,20 @@
9595
Route::get('task/create', 'TaskController@create');
9696
Route::post('task', 'TaskController@store');
9797

98-
Route::resource('post', 'PostController');
98+
Route::resource('post', 'PostController');
99+
100+
Route::get('task/{id}', function ($id) {
101+
$task = \App\Models\Task::findOrFail($id);
102+
});
103+
104+
Route::get('task/{task}', function (\App\Models\Task $task) {
105+
dd($task);
106+
});
107+
108+
Route::get('task/model/{task_model}', function (\App\Models\Task $task) {
109+
dd($task);
110+
});
111+
112+
Route::fallback(function () {
113+
return '我是最后的屏障';
114+
});

0 commit comments

Comments
 (0)