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

resources/views/posts/index.blade.php

                <td><a href="{{ route('posts.edit', $post->id) }}">edit</a> | hapus | lihat</td>

@rawaludin
Copy link
Author

app/Http/Controllers/PostController.php

    public function edit(Post $post)
    {
        return view('posts.edit', compact('post'));
    }

@rawaludin
Copy link
Author

resources/views/posts/edit.blade.php

Halaman edit untuk post {{ $post->id }}

@rawaludin
Copy link
Author

resources/views/posts/edit.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        {!! Form::model($post, ['route' => ['posts.update', $post->id], 'method' => 'put']) !!}
            <div class="form-group">
                {!! Form::label('Judul') !!}
                {!! Form::text('title', null, ['class' => 'form-control', 'placeholder' => 'Judul tulisan']) !!}
            </div>
            <div class="form-group">
                {!! Form::label('Konten') !!}
                {!! Form::textarea('content', null, ['class' => 'form-control', 'placeholder' => 'Isi artikel']) !!}
            </div>
            {!! Form::submit('Simpan', ['class' => 'btn btn-default']) !!}
		{!! Form::close() !!} 
    </div>
</div>
@endsection

@rawaludin
Copy link
Author

@rawaludin
Copy link
Author

resources/views/posts/_form.blade.php

<div class="form-group">
    {!! Form::label('Judul') !!}
    {!! Form::text('title', null, ['class' => 'form-control', 'placeholder' => 'Judul tulisan']) !!}
</div>
<div class="form-group">
    {!! Form::label('Konten') !!}
    {!! Form::textarea('content', null, ['class' => 'form-control', 'placeholder' => 'Isi artikel']) !!}
</div>
{!! Form::submit('Simpan', ['class' => 'btn btn-default']) !!}

@rawaludin
Copy link
Author

resources/views/posts/create.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        {!! Form::open(['route' => 'posts.store']) !!}
            @include('posts._form')
		{!! Form::close() !!} 
    </div>
</div>
@endsection

resources/views/posts/edit.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        {!! Form::model($post, ['route' => ['posts.update', $post->id], 'method' => 'put']) !!}
            @include('posts._form')
		{!! Form::close() !!} 
    </div>
</div>
@endsection

@rawaludin
Copy link
Author

app/Http/Controllers/PostController.php

public function update(Request $request, Post $post)
    {
        $post->update($request->all());
        return redirect()->route('posts.index');
    }

@rawaludin
Copy link
Author

resources/views/posts/index.blade.php

                <td><a href="{{ route('posts.edit', $post->id) }}">edit</a> | hapus | <a href="/posts/{{ $post->id }}">lihat</a></td>

@rawaludin
Copy link
Author

resources/views/posts/index.blade.php

            <td>
                {!! Form::model($post, ['route' => ['posts.destroy', $post->id], 'method' => 'delete', 'class' => 'form-inline'] ) !!}
                    <a href="/manage/posts/{{ $post->id }}/edit">ubah</a> |
                    {!! Form::submit('hapus', ['class'=>'btn btn-xs btn-danger']) !!}
                    | <a href="/article/{{$post->id}}">lihat</a>
                {!! Form::close()!!}
            </td>

app/Http/Controllers/PostController.php

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

@rawaludin
Copy link
Author

database/migrations/2017_10_10_073835_create_posts_table.php

    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('content');
            $table->integer('author_id')->unsigned();
            $table->timestamps();

            $table->foreign('author_id')->references('id')->on('users')
                ->onUpdate('restrict')->onDelete('cascade');
        });
    }

@rawaludin
Copy link
Author

rawaludin commented Oct 19, 2017

database/seeds/PostsTableSeeder.php

public function run()
    {
        $users = App\User::all();
        foreach (range(1,20) as $counter) {
            factory(App\Post::class)->create(['author_id' => $users->random()->id]);
        }
    }
php artisan migrate:refresh --seed

@rawaludin
Copy link
Author

database/factories/Post.php

<?php

use Faker\Generator as Faker;
use App\Post;

$factory->define(Post::class, function (Faker $faker) {
    return [
        'title' => $faker->sentence,
        'content' => $faker->paragraph,
        'author_id' => rand(1,3)
    ];
});

@rawaludin
Copy link
Author

app/Post.php

public function author()
    {
        return $this->belongsTo(User::class, 'author_id');
    }

resources/views/blogs/index.blade.php

                <div class="panel-heading">
                    <a href="/posts/{{$post->id}}">{{$post->title}}</a>
ditulis oleh {{ $post->author->name }}
                </div>

@rawaludin
Copy link
Author

resources/views/layouts/app.blade.php:39

<li><a href="{{ route('posts.index') }}">Tulisan</a></li>

@rawaludin
Copy link
Author

app/Http/Controllers/PostController.php

    public function store(Request $request)
    {
        $post = new Post();
        $post->title = $request->input('title');
        $post->content = $request->input('content');
        $post->author_id = $request->user()->id;
        $post->save();
        return redirect()->route('posts.index');
    }
public function update(Request $request, Post $post)
    {
        $post->update($request->only('title', 'content'));
        return redirect()->route('posts.index');
    }

@rawaludin
Copy link
Author

database/seeds/UsersTableSeeder.php

<?php

use Illuminate\Database\Seeder;
use App\User;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds
     * @return void
     */
    public function run()
    {
        factory(User::class)->create([
            'name' => 'Admin Ganteng',
            'email' => 'admin@gmail.com',
            'password' => bcrypt('rahasia'),
            'level' => User::LEVEL_ADMIN,
        ]);

        factory(User::class)->create([
            'name' => 'Member Kece',
            'email' => 'kece@gmail.com',
            'password' => bcrypt('rahasia'),
            'level' => User::LEVEL_MEMBER,
        ]);

        factory(User::class)->create([
            'name' => 'Member Keren',
            'email' => 'keren@gmail.com',
            'password' => bcrypt('rahasia'),
            'level' => User::LEVEL_MEMBER,
        ]);
    }
}

@rawaludin
Copy link
Author

app/User.php

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    const LEVEL_ADMIN = 1;
    const LEVEL_MEMBER = 2;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'level'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

database/migrations/2014_10_12_000000_create_users_table.php

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->smallInteger('level');
            $table->rememberToken();
            $table->timestamps();
        });
    }

@rawaludin
Copy link
Author

app/Http/Controllers/Auth/RegisterController.php

protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'level' => User::LEVEL_MEMBER,
        ]);
    }

@rawaludin
Copy link
Author

app/User.php

    public function isAdmin()
    {
        return $this->level == static::LEVEL_ADMIN;
    }

    public function isMember()
    {
        return $this->level == static::LEVEL_MEMBER;
    }

app/Http/Controllers/PostController.php

public function index(Request $request)
    {
        if ($request->user()->isMember()) {
            $posts = Post::where('author_id', $request->user()->id)->paginate(20);
        }
        if ($request->user()->isAdmin()) {
            $posts = Post::paginate(20);
        }
        return view('posts.index', compact('posts'));
    }

@rawaludin
Copy link
Author

app/User.php

public function posts()
    {
        return $this->hasMany(Post::class, 'author_id');
    }

app/Http/Controllers/PostController.php

public function index(Request $request)
    {
        if ($request->user()->isMember()) {
            $posts = $request->user()->posts()->paginate(20);
        }
        if ($request->user()->isAdmin()) {
            $posts = Post::paginate(20);
        }
        return view('posts.index', compact('posts'));
    }

@rawaludin
Copy link
Author

app/Providers/AuthServiceProvider.php

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

@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