ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
建表:php artisan make:migration create_tasks_table --create=tasks 建模型:php artisan make:model Task 一个User实例对应多个Task实例,而一个Task实例从属于某个User: /** * Get all of the tasks for the user. */ public function tasks() { return $this->hasMany(Task::class); } public function user() { return $this->belongsTo(User::class); } 路由: Route::group(['middleware' => ['web']], function () { Route::get('/', function () { return view('welcome'); })->middleware('guest'); Route::get('/tasks', 'TaskController@index'); Route::post('/task', 'TaskController@store'); Route::delete('/task/{task}', 'TaskController@destroy'); Route::auth(); }); 设置中间件: class TaskController extends Controller{ /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } } 依赖注入: 我们创建一个app/Repositories目录并在其中创建一个TaskRepository类。记住,Laravel项目的app文件夹下的所有目录都使用 PSR-4 自动加载标准被自动加载,所以你可以在其中随心所欲地创建需要的目录: ~~~ <?php namespace App\Repositories; use App\User; use App\Task; class TaskRepository{ /** * Get all of the tasks for a given user. * * @param User $user * @return Collection */ public function forUser(User $user) { return Task::where('user_id', $user->id) ->orderBy('created_at', 'asc') ->get(); } } public function __construct(TaskRepository $tasks) { $this->middleware('auth'); $this->tasks = $tasks; } 授权: php artisan make:policy TaskPolicy class TaskPolicy{ use HandlesAuthorization; /** * Determine if the given user can delete the given task. * * @param User $user * @param Task $task * @return bool */ public function destroy(User $user, Task $task) { return $user->id === $task->user_id; } } 最后,我们需要关联Task模型和TaskPolicy,这可以通过在app/Providers/AuthServiceProvider.php文件的policies属性中添加注册来实现,注册后会告知Laravel无论何时我们尝试授权动作到Task实例时该使用哪个策略类进行判断: /** * The policy mappings for the application. * * @var array */ protected $policies = [ 'App\Task' => 'App\Policies\TaskPolicy', ]; ~~~