YuHo のブログ

Laravel, PHP, JavaScript

Laravel 5.6 でブログサイトを制作する #8

Post の Update に Authorization を付ける

//App\Providers\AuthServiceProvider

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        Gate::define('update-post', function ($user, $post) {
            return $user->id == $post->user_id;
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}
//PostController

<?php

public function update(Request $request, Post $post)
{
    if (Gate::allows('update-post', $post)) {
        return redirect('/');
    }

    $post->title = $request->input('title');
    $post->content = $request->input('content');

    $post->save();

    return redirect('/');
}