How to make CRUD Laravel 8 clean Code for beginner

Cahyo Fajar Pamungkas
6 min readOct 7, 2021

--

Hello everybody, I write a tutorial about How to make CRUD laravel 8

if you have trouble learning laravel this tutorial is perfect for you

okee first we can install laravel with code in the below

so before you install laravel with this code make sure you have composer installed in your computer

first

composer create-project — prefer-dist laravel/laravel project_name

if you are using xampp, go to the folder xampp/htdoc/project_name

and open the folder app

if you are using Laragon, go to the folder laragon/www/project_name

Open this app, I use Visual studio code for this text editor

Next we can open cmd and start the app with

php artisan serve

Wow amazing app,

next we can start make model,controller and database in the same time with this magic code

php artisan make:model Post -mc

we can add -mc (M for model and C for controller)

open folder if you want to see model

Model : app/models/Post.php

Controller : app/Http/controllers/PostController.php

Migration : database/migrations/2021_10_07_032242_create_posts_table

Oke let’s start make sure you have created a database

change .env file and search DB_DATABASE= your database

Open migration file and change like below :

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create(‘posts’, function (Blueprint $table) {
$table->id();
$table->string(‘title’);
$table->text(‘post_content’);
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists(‘posts’);
}
}

let’s start with this code to make migration

php artisan migrate

oke we have created tables

you can check to your database there is multiple tables.

next add property in model Post.php

Add protected $guarded = [];

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Database\Eloquent\Model;

class Post extends Model

{

use HasFactory;

protected $guarded = [];

}

Oke next to write code

open your browser with link like http://127.0.0.1:8000

oke we have opened laravel project, oke next

open route file : routes/web.php

change with this

I just add namespace for the route like this

namespace App\Http\Controllers;

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Route;

Route::get(‘/’, function () {

return view(‘welcome’);

});

Route::get(‘/post’,[PostController::class,’index’])->name(‘post.index’);

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

Route::post(‘/post’,[PostController::class,’store’])->name(‘post.store’);

Route::get(‘/post/{post}/edit’,[PostController::class,’edit’])->name(‘post.edit’);

Route::put(‘/post/{post}/update’,[PostController::class,’update’])->name(‘post.update’);

Route::delete(‘/post/{post}/delete’,[PostController::class,’destroy’])->name(‘post.destroy’);

next open PostController.php

change to this :

Code : copy this text to your text editor

<?php

namespace App\Http\Controllers;

use App\Models\Post;

use Illuminate\Http\Request;

class PostController extends Controller

{

public function index()

{

$posts = Post::all();

return view(‘post.index’,compact(‘posts’));

}

public function create()

{

return view(‘post.create’);

}

public function store(Request $request)

{

$this->validate($request,[

‘title’ => ‘required’,

‘post_content’ => ‘required’

]);

$data = $request->all();

Post::create($data);

return redirect()->route(‘post.index’)->with(‘success’,’Success created post’);

}

public function edit(Request $request,Post $post)

{

return view(‘post.edit’,compact(‘post’));

}

public function update(Request $request,Post $post)

{

$this->validate($request,[

‘title’ => ‘required’,

‘post_content’ => ‘required’

]);

$data = $request->all();

$post->update($data);

return redirect()->route(‘post.index’)->with(‘success’,’Success updated post’);

}

public function destroy(Request $request,Post $post)

{

if($post){

$post->delete();

return redirect()->route(‘post.index’)->with(‘success’,’Success deleted post’);

}

}

}

Next, I can make content with dynamic content with @yield

open folder resources/views/ create folder post

resources/views/post

again, create folder layouts inside views

the structure is like this

And then create file like below

first open folder layouts/app.php

I use bootstart 4 for UI you can copy in the link below

!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”>

<link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity=”sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm” crossorigin=”anonymous”>

<title>Post CRUD</title>

</head>

<body>

// yield for dynamic content

@yield(‘content’)

<script src=”https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity=”sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN” crossorigin=”anonymous”></script>

<script src=”https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity=”sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q” crossorigin=”anonymous”></script>

<script src=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity=”sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl” crossorigin=”anonymous”></script>

</body>

</html>

Next step, open index file in the post folder resources/views/post/index.blade.php

change with this :

I use @extends call to layouts.app

and and to add content to yield we can use @section(‘content’)

Code :

@extends(‘layouts.app’)

@section(‘content’)

<section class=”container”>

@if (Session::has(‘success’))

<div class=”alert alert-success mt-3">

{{ Session::get(‘success’) }}

</div>

@endif

<div class=”card mt-5">

<div class=”card-header”>

<h5>Data Post</h5>

</div>

<div class=”card-body”>

<a href=”{{ route(‘post.create’) }}” class=”btn btn-success mb-3">+ Create Post</a>

<div class=”table-responsive”>

<table class=”table table-striped table-inverse table-responsive d-table”>

<thead>

<tr>

<th>No</th>

<th>Title</th>

<th>Content</th>

<th>Action</th>

</tr>

</thead>

<tbody>

<?php $no = 1; ?>

@forelse ($posts as $post)

<tr>

<td>{{ $no++ }}</td>

<td>{{ $post->title }}</td>

<td>{{ $post->post_content }}</td>

<td>

<a href=”{{ route(‘post.edit’,$post) }}” class=”btn btn-warning btn-sm”>Edit</a>

<form action=”{{ route(‘post.destroy’,$post) }}” method=”post” style=”display: contents;”>

@csrf

@method(‘DELETE’)

<button type=”submit” class=”btn btn-danger btn-sm”>Delete</button>

</form>

</td>

</tr>

@empty

<tr>

<td colspan=”4">No data.</td>

</tr>

@endforelse

</tbody>

</table>

</div>

</div>

</div>

</section>

@endsection

Next step, open create file in the post folder resources/views/post/create.blade.php

Change like this :

Code :

@extends(‘layouts.app’)

@section(‘content’)

<section class=”container”>

<div class=”card mt-5">

<div class=”card-header”>

<h5>Create Post</h5>

</div>

<div class=”card-body”>

@if ($errors->any())

<div class=”alert alert-danger”>

<ul>

@foreach ($errors->all() as $error)

<li>{{ $error }}</li>

@endforeach

</ul>

</div>

@endif

<form action=”{{ route(‘post.store’) }}” method=”post”>

@csrf

<div class=”form-group”>

<label for=””>Title</label>

<input type=”text” name=”title” value=”{{ old(‘title’) }}” class=”form-control” placeholder=”Title Post”>

</div>

<div class=”form-group”>

<label for=””>Post Content</label>

<textarea name=”post_content” value=”{{ old(‘post_content’) }}” class=”form-control” placeholder=”Post Content”></textarea>

</div>

<button type=”submit” class=”btn btn-success”>CREATE</button>

</form>

</div>

</div>

</section>

@endsection

Last step, open edit file in the post folder resources/views/post/edit.blade.php

Code like below :

@extends(‘layouts.app’)

@section(‘content’)

<section class=”container”>

<div class=”card mt-5">

<div class=”card-header”>

<h5>Update Post</h5>

</div>

<div class=”card-body”>

@if ($errors->any())

<div class=”alert alert-danger”>

<ul>

@foreach ($errors->all() as $error)

<li>{{ $error }}</li>

@endforeach

</ul>

</div>

@endif

<form action=”{{ route(‘post.update’,$post) }}” method=”post”>

@method(‘PUT’)

@csrf

<div class=”form-group”>

<label for=””>Title</label>

<input type=”text” name=”title” value=”{{ old(‘title’,$post->title) }}” class=”form-control” placeholder=”Title Post”>

</div>

<div class=”form-group”>

<label for=””>Post Content</label>

<textarea name=”post_content” value=”” class=”form-control” placeholder=”Post Content”>{{ old(‘post_content’,$post->post_content) }}</textarea>

</div>

<button type=”submit” class=”btn btn-success”>UDPATE</button>

</form>

</div>

</div>

</section>

@endsection

Oke finish, you just created a laravel project with clean code, but I don’t use the route resource, if you want to use it, you can use a code like this

php artisan make:controller PostController -r

and then route file just

Route::resource(‘post’,PostController::class);

oke, Thank you for reading this tutorial, hopefully friends are always healthy and happy. See you next tutorial

--

--

Cahyo Fajar Pamungkas

I'm Fullstack web developer and I’m still learning, I interested with new teck stack