Skip to content

Instantly share code, notes, and snippets.

@rawaludin
Created October 19, 2017 06:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rawaludin/3723fd5558258d89b80a8a61beea3c47 to your computer and use it in GitHub Desktop.
Save rawaludin/3723fd5558258d89b80a8a61beea3c47 to your computer and use it in GitHub Desktop.
@rawaludin
Copy link
Author

app/Policies/PostPolicy.php

    public function update(User $user, Post $post)
    {
        return $post->author_id == $user->id;
    }

@rawaludin
Copy link
Author

app/Http/Controllers/PostController.php

public function edit(Post $post)
    {
        $this->authorize('update', $post);
        return view('posts.edit', compact('post'));
    }

@rawaludin
Copy link
Author

resources/views/errors/403.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <p>
        Maaf Anda tidak punya akses untuk halaman ini.
    </p>
</div>
@endsection

@rawaludin
Copy link
Author

app/Providers/AuthServiceProvider.php

use App\Post;
use App\Policies\PostPolicy;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        Post::class => PostPolicy::class
    ];

app/Policies/PostPolicy.php

public function update(User $user, Post $post)
    {
        if ($user->isAdmin())  {
            return true;
        }

        return $post->author_id == $user->id;
    }

@rawaludin
Copy link
Author

app/Policies/PostPolicy.php

public function delete(User $user, Post $post)
    {
        if ($user->isAdmin())  {
            return true;
        }

        return $post->author_id == $user->id;
    }

app/Http/Controllers/PostController.php

public function destroy(Post $post)
    {
        $this->authorize('delete', $post);
        $post->delete();
        return redirect()->route('posts.index');
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment