Laravel is a web framework of PHP, Widely being used by many developers. if you are new to Laravel this article will surely help you out creating, updating, deleting a blog. Let’s dive in and see simple CRUD application in Laravel. I have created a repository on Github of this project. At the end of the article, I will add the GitHub link to this project. Before you clone this project from GitHub, I will recommend reading the article first.
Yes, I am going to create a blog site where you can create new blog posts, update posts, delete posts.
I assume you have done the setup of laravel, if not then you can read this article on how to install and setup Laravel.
Database Configuration
After installation, you will see the .env file in your project. This is the file where we do the configuration setting. In this file, we will save our database configuration. Open .env file and update this information.
...
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=YOUR_DATABASE_NAME
DB_USERNAME=root
DB_PASSWORD=YOUR _DB_PASSWORD
...
Create Migration (table) , Model , Controller
You can create migration aka table, Model, and controller with one single command. Type the following command in your cmd or terminal. I am creating with name “Blog”, you can name it whatever you want. Make sure you follow the practice and always make first letter capital.
php artisan make:model Blog -mcr
Now we have Model, Controller, and Migration in their respective folders. So now let’s open our migration because this is where we add our columns in the table . You can find the migrations in the “database/migrations” folder. Open the file in migrations we just created and add columns like the following.
....
public function up()
{
Schema::create('blogs', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('description');
$table->timestamps();
});
}
....
I have added the “title” and “description” field in my migration field. Now to add this table with these columns in the database, we will run the following command.
php artisan migrate
Model setup
Now open model with the name “Blog.php”. You can find it inside the “app” directory. Open it and add the columns you will be populating while you create blogs. I have “title” and “description” to add to the model.
class Blog extends Model
{
protected $fillable = ['title','description'];
}
Controller setup
Now open controller with the file name “BlogController.php”. Which is locatable at “app/Http/Controllers/”. Open it and you will see a bunch of functions already present, it is because we executed command with “-mcr” above. Now, let’s add some codes to each function.
class BlogController extends Controller
{
public function index()
{
$blogs = Blog::all();
return view('blogs.index',compact('blogs'));
}
public function create()
{
return view('blogs.create');
}
public function store(Request $request)
{
$request->validate([
'title' => 'required',
'description' => 'required',
]);
$blog = Blog::create(['title' => $request->title,'description' => $request->description]);
return redirect('/blog/'.$blog->id);
}
public function update(Request $request)
{
$request->validate([
'title' => 'required',
'description' => 'required',
]);
$blog = Blog::where('id',$request->id)->update(['title' => $request->title,'description' => $request->description]);
return redirect('/blog/'.$request->id);
}
public function show(Request $request )
{
$blog = Blog :: findOrFail($request->id);
return view('blogs.show',compact('blog'));
}
public function edit(Request $request )
{
$blog = Blog :: findOrFail($request->id);
return view('blogs.edit',compact('blog'));
}
public function destroy(Request $request , Blog $blog)
{
$blog = Blog::find($request->id);
$blog->delete();
return redirect('/');
}
}
Don’t worry about all bunch of codes, we will use one function at a time. as you have noticed we are calling view() in a few functions in our controller. We need to create view files for the view() functions like index.blade.php, create.blade.php, edit.blade.php, show.blade.php. we will create this view files inside a folder named blogs that will reside in “resources/views”directory.
View Setup
Before we create CRUD views lets create one common file “layout.blade.php”. I am using bootstrap for UI purposes. This file will contain our navigation part and bootstrap links. Add these lines of code in layout.blade.php and this file will be in “views/” directory.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
</head>
<body>
<nav class="navbar navbar-expand-sm bg-light">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="{{route('home')}}">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{route('create')}}">Add New Post</a>
</li>
</ul>
</nav>
<br>
<div class="container-fluid">
@yield('content')
</div>
</body>
</html>
Now open “views/blogs/index.blade.php” and add these lines of code
@extends('layout')
@section('content')
<div class="container">
<h1>All Blogs</h1>
<hr>
<table class="table">
<thead>
<tr>
<th>id</th>
<th>Title</th>
<th>Description</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@if($blogs)
@foreach($blogs as $blog)
<tr>
<td>{{$blog->id}}</td>
<td>{{$blog->title}}</td>
<td>{{$blog->description}}</td>
<td>
<a href="{{route('edit',$blog->id)}}" class="btn btn-primary">Edit</a>
<form action="{{url('delete/blog', [$blog->id])}}" method="POST">
<input type="hidden" name="_method" value="DELETE">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="submit" class="btn btn-danger" value="Delete"/>
</form>
</td>
</tr>
@endforeach
@endif
</tbody>
</table>
</div>
@endsection
Next open “views/blogs/create.blade.php” and add these lines of code
@extends('layout')
@section('content')
<div class="row">
<div class="col-md-4">
<h1>Add New Blog</h1>
<hr>
<form action="{{route('store')}}" method="post">
{{ csrf_field() }}
<div class="form-group">
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<label for="title"> Title</label>
<input type="text" class="form-control" id="title" name="title">
</div>
<div class="form-group">
<label for="description">Description</label>
<input type="text" class="form-control" id="description" name="description">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
@endsection
Open “views/blogs/show.blade.php” and add these lines of code
@extends('layout')
@section('content')
<h1>Showing Blog - {{ $blog->title }}</h1>
<div class=" card col-md-4">
<p>
<strong>Title:</strong> {{ $blog->title }}<br>
<strong>Description:</strong> {{ $blog->description }}
</p>
</div>
@endsection
Finally open “views/blogs/edit.blade.php” and add these lines of code
@extends('layout')
@section('content')
<div class="row">
<div class="col-md-4">
<h1>Edit Blog</h1>
<hr>
<form action="{{route('update', $blog->id)}}" method="POST">
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<input type="hidden" name="_method" value="PUT">
<input type="hidden" name="id" value="{{$blog->id}}">
{{ csrf_field() }}
<div class="form-group">
<label for="title">Task Title</label>
<input type="text" value="{{$blog->title}}" class="form-control" id="taskTitle" name="title" >
</div>
<div class="form-group">
<label for="description">Task Description</label>
<input type="text" value="{{$blog->description}}" class="form-control" id="taskDescription" name="description" >
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
@endsection
Finally everything is on right place , lets add routing in “routes/web.php”
Route::get('/', 'BlogController@index')->name('home');
Route::get('/blog/{id}','BlogController@show')->name('show');
Route::get('/create','BlogController@create')->name('create');
Route::post('/store','BlogController@store')->name('store');
Route::get('/edit/blog/{id}','BlogController@edit')->name('edit');
Route::put('/edit/blog/{id}','BlogController@update')->name('update');
Route::delete('/delete/blog/{id}','BlogController@destroy')->name('delete');
start the server by running command .
php artisan serve
Conclusion
So the article is completed with CRUD functionality. It covers everything you need to create a fully functional simple CRUD application in Laravel. It is important for each developer to know at least about creating, updating, and deleting data. Now you have read and followed the article. Clone the repository and try experimenting on it.
If you get any problems following the article and get any error that is mentioned in this article, feel free to leave comments in below comments section
