0% found this document useful (0 votes)
6 views8 pages

Modul Belajar Laravel Part 3

The document provides a step-by-step guide for creating a like and comment feature in a Laravel application. It includes instructions for creating models, updating the PostController, modifying web routes, and adjusting Blade templates to display posts and comments. Additionally, it outlines the necessary database migrations and model relationships to support the new functionality.

Uploaded by

Ujang K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views8 pages

Modul Belajar Laravel Part 3

The document provides a step-by-step guide for creating a like and comment feature in a Laravel application. It includes instructions for creating models, updating the PostController, modifying web routes, and adjusting Blade templates to display posts and comments. Additionally, it outlines the necessary database migrations and model relationships to support the new functionality.

Uploaded by

Ujang K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

MODUL UKK PART 3

MEMBUAT LIKE DAN KOMENTAR


1. Buat model like dan comment di terminal
php artisan make:model like -m
php artisan make:model comment –m
2. Kemudian pada 2024 create like tambahkan script berikut
public function up(): void
{
Schema::create('likes', function (Blueprint $table) {
$table->id();
//tambahkan yang ini
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->foreignId('post_id')->constrained()->onDelete('cascade');
//sampai sini
$table->timestamps();
});
3. Pada 2024 create comment tambahkan script berikut
public function up(): void
{
Schema::create('comments', function (Blueprint $table) {
$table->id();
//tambahkan yang ini
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->foreignId('post_id')->constrained()->onDelete('cascade');
$table->text('content');
//sampai sini
$table->timestamps();
});

4. Kemudian di PostController ubah menjadi seperti ini

<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Post;
use App\Models\Like;
use App\Models\Comment;

//return type View


use Illuminate\View\View;
use Illuminate\Http\Request;
class PostController extends Controller
{
//
public function index(): View
{
$posts=Post::all();
return view('posts.index', compact('posts'));
}
public function store(Request $request)
{
$request->validate([
'image'=>'required|image|mimes:jpeg,png,jpg,gif|max:2048',
'caption'=>'required|string|max:255',
]);
$image=$request->file('image');
$imageName=time() . '.' . $image->extension();
$image->move(public_path('images'), $imageName);
Post::create([
'image'=>$imageName,
'caption'=>$request->caption,
]);
return redirect('posts')->with('success', 'Data telah di tambahkan.');
}
public function create(): View
{
return view('posts.create');
}
public function like(Post $post)
{

$post->likes()->attach(auth()->id());
return redirect()->back()->with('success', 'Postingan disukai. ');

}
public function unlike(Post $post)
{
$post->likes()->detach(auth()->id());
return redirect()->back()->with('success', 'Postingan batal disukai. ');
}
public function comment(Request $request)
{
$request->validate([
'post_id'=> 'required|exists:posts,id',
'content'=> 'required|string',
]);
Comment::create([
'post_id'=> $request->post_id,
'user_id'=> auth()->id(),
'content'=> $request->content,
]);
return redirect()->back()->with('success', 'Komentar ditambahkan. ');
}
public function show(string $id): View
{
//get post by ID
$post = Post::findOrFail($id);

//render view with post


return view('posts.show', compact('post'));
}
}

5. Kemudian buka web.php lalu ubah seperti berikut.

<?php

use App\Http\Controllers\AdminController;
use App\Http\Controllers\AuthController;
use App\Http\Controllers\UserController;
use App\Http\Controllers\PostController;
use App\Models\User;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/
Route::get('/', function () {
return view('welcome');
});

Route::get('/dashboard', function () {
return view('dashboard');
});

Route::get('login', [AuthController::class,'index'])->name('login');
Route::get('register', [AuthController::class,'register'])->name('register');
Route::post('proses_login', [AuthController::class,'proses_login'])->name('proses_login');
Route::get('logout', [AuthController::class,'logout'])->name('logout');

Route::post('proses_register',[AuthController::class,'proses_register'])->name('proses_register');

// kita atur juga untuk middleware menggunakan group pada routing


// didalamnya terdapat group untuk mengecek kondisi login
// jika user yang login merupakan admin maka akan diarahkan ke AdminController
// jika user yang login merupakan user biasa maka akan diarahkan ke UserController
Route::group(['middleware' => ['auth']], function () {
Route::group(['middleware' => ['cek_login:admin']], function () {
Route::resource('admin', AdminController::class);
});
Route::group(['middleware' => ['cek_login:user']], function () {
Route::resource('user', UserController::class);
});
});

Route::get('/post/create', [PostController::class, 'create'])->name('post.create');


Route::post('/post', [PostController::class, 'store'])->name('post.store');
Route::resource('/posts', \App\Http\Controllers\PostController::class);
Route::post('/post/{post}/like',[PostController::class, 'like'])->name('post.like');
Route::post('/comment', [PostController::class, 'comment'])->name('comment.store');

6. Buka index.blade.php pada folder posts kemudian ubah kode programnya menjadi
seperti ini

<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Postingan</title>
</head>
<body>

<h1>Daftar Postingan Foto</h1>


<h2> <a href="/dashboard">Beranda</a></h2>
@if(session('success'))
<div>{{ session('success') }}</div>
@endif
<div>
<a href="{{ route('post.create') }}">Tambah Postingan</a>
</div>
<div>
@foreach($posts as $post)
<div>
<a href="{{ route('posts.show', $post->id) }}" class="btn btn-sm btn-
dark"><img src="{{ asset('images/' . $post->image) }}" alt="{{ $post->caption }}"
width="300"></a>
<p>{{ $post->caption }}</p>
<p>Jumlah Likes:<b> {{ isset($post->likes) ? $post->likes->count() : 0 }}
</b></p>
<form action="{{ route('post.like', $post->id) }}" method="POST">
@csrf
<button type="submit">Like</button>
</form>
<p>{{ $post->content }}</p>

@if($post->comments->isNotEmpty())
<h3>Komentar: <b> {{ isset($post->comments) ? $post->comments->count() : 0 }}
</b></h3>

@else
<p>Tidak ada komentar</p>
@endif

<form action="{{ route('comment.store') }}" method="POST">


@csrf
<input type="hidden" name="post_id" value="{{ $post->id }}">
<input type="text" name="content" placeholder="Tambah Komentar">
<button type="submit">Komentar</button>
</form>
</div>
@endforeach
</div>
</body>
</html>

7. Buka model/Post lalu ubah kode programnya seperti berikut

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model


{
use HasFactory;
protected $fillable = [
'image',
'caption',
];
protected $with = ['likes'];
public function likes()
{
return $this->belongsToMany(User::class, 'likes', 'post_id', 'user_id');
}

public function comments()


{
return $this->hasMany(Comment::class);
}
}

8. Buka model/Comment, kemudian ubah kode programnya seperti berikut.

<?php

namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Comment extends Model


{
use HasFactory;
protected $fillable=[
'content',
'user_id',
'post_id',
];
public function user()
{
return $this->belongsTo(User::class);
}
}

9. Buat file baru pada Views/posts dengan nama show.blade.php kemudian buat kode
programnya seperti berikut.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Detail Data Postingan</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body style="background: lightgray">

<div class="container mt-5 mb-5">


<div class="row justify-content-center">
<div class="col-md-8">
<div class="card border-0 shadow-sm rounded">
<div class="card-body">
<a href="/posts">Kembali</a>
<img src="{{ asset('images/'.$post->image) }}" class="w-100
rounded">

<p>{{ $post->content }}</p>


@if($post->comments->isNotEmpty())
<h3>Komentar:</h3>

@foreach($post->comments as $comment)
<p><strong>{{ $comment->user->name }}</strong>:{{ $comment->content }}</p>
@endforeach
@else
<p>Tidak ada komentar</p>
@endif
<hr>
<p class="tmt-3">
{!! $post->content !!}
</p>
</div>
</div>
</div>
</div>
</div>

<script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></scrip
t>
</body>
</html>

Pada terminal ketikan


php artisan migrate
untuk migrasi table yang baru
Kemudian uji coba hasilnya

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy