In this tutorial, we will be creating a CRUD (Create, Read, Update, and Delete) application using Laravel 8, the latest version of the popular PHP framework. Laravel 8 offers several new features and Long-Term Support (LTS), making it a great choice for beginners who are new to the framework.
The tutorial will guide you through the process of building a basic CRUD application from scratch, using controllers, models, routes, Bootstrap 4, and the Blade template engine. By the end of this tutorial, you will have a solid understanding of how to create a CRUD application in Laravel 8.
Table of Contents
Step 1: Install Laravel 8
The first step is to install a fresh version of Laravel 8. To do this, open your terminal or command prompt and run the following command:
composer create-project --prefer-dist laravel/laravel blog
This command will create a new Laravel 8 project called “blog”.
Step 2: Database Configuration
In the second step, we will configure the database for our CRUD application. We will need to specify the database name, username, and password. To do this, open the .env file in the root of your project and update the following fields:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=DATA_BASE_NAME
DB_USERNAME=root
DB_PASSWORD=YOUR_DB_PASSWORD
Make sure to replace the placeholder values with your actual database information. Once you have done this, you will be able to connect to your database and begin creating the CRUD application.
Note: The above steps are the basic setup that you need to follow in order to create a CRUD application in laravel 8. The tutorial will continue with the next steps like creating migration, model, controller, route and views.
Step 3: Create Migration
In this step, we will create a migration for the “products” table using the Laravel 8 php artisan command. To create the migration, run the following command:
php artisan make:migration create_products_table --create=products
This command will create a new file in the “database/migrations” directory. In this file, you will find a class called “CreateProductsTable” which will contain the code for creating the products table. You should add the following code to this file:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('detail');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('products');
}
}
This code will create a “products” table with an “id”, “name”, “detail” and timestamps fields. Once you have added this code, you can run the following command to create the table in the database:
php artisan migrate
Step 4: Add Resource Route
In this step, we will add a resource route for the product CRUD application. To do this, open the “routes/web.php” file and add the following route:
use App\Http\Controllers\ProductController;
Route::resource('products', ProductController::class);
This will create routes for all the CRUD operations using the ProductController.
Step 5: Add Controller and Model
In this step, we will create a new controller called ProductController. To do this, run the following command:
php artisan make:controller ProductController --resource --model=Product
This command will create a new file in the “app/Http/Controllers” directory called “ProductController.php”. It will also create a new model called “Product” in the “app/Models” directory. The controller will have seven methods by default: index(), create(), store(), show(), edit(), update(), and destroy().
Copy the following code and paste it into the “ProductController.php” file:
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use Illuminate\Http\Request;
class ProductController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$products = Product::latest()->paginate(5);
return view('products.index',compact('products'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('products.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'detail' => 'required',
]);
Product::create($request->all());
return redirect()->route('products.index')
->with('success','Product created successfully.');
}
/**
* Display the specified resource.
*
* @param \App\Product $product
* @return \Illuminate\Http\Response
*/
public function show(Product $product)
{
return view('products.show',compact('product'));
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Product $product
* @return \Illuminate\Http\Response
*/
public function edit(Product $product)
{
return view('products.edit',compact('product'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Product $product
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Product $product)
{
$request->validate([
'name' => 'required',
'detail' => 'required',
]);
$product->update($request->all());
return redirect()->route('products.index')
->with('success','Product updated successfully');
}
/**
* Remove the specified resource from storage.
*
* @param \App\Product $product
* @return \Illuminate\Http\Response
*/
public function destroy(Product $product)
{
$product->delete();
return redirect()->route('products.index')
->with('success','Product deleted successfully');
}
}
This code will handle all the CRUD operations for the “products” table. The index() method will retrieve all the products from the database and pass them to the “products.index” view, the create() method will return the “products.create” view, the store() method will insert a new product into the database, the show() method will retrieve a specific product from the database and pass it to the “products.show” view, the edit() method will retrieve a specific product from the database and pass it to the “products.edit” view, the update() method will update a specific product in the database, and the destroy() method will delete a specific product from the database.
app/Models/Product.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
protected $fillable = [
'name', 'detail'
];
}
In order to complete this tutorial, you will also need to create views for each of the CRUD operations. These views will be used to display the data to the user and handle form submissions. You can use the Blade template engine to create these views. You should create a new directory called “products” within the “resources/views” directory and create the following views:
- index.blade.php
- create.blade.php
- show.blade.php
- edit.blade.php
resources/views/products/layout.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 8 CRUD Application - ItSolutionStuff.com</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet">
</head>
<body>
<div class="container">
@yield('content')
</div>
</body>
</html>
resources/views/products/index.blade.php
@extends('products.layout')
@section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Laravel 8 CRUD Example from scratch - ItSolutionStuff.com</h2>
</div>
<div class="pull-right">
<a class="btn btn-success" href="{{ route('products.create') }}"> Create New Product</a>
</div>
</div>
</div>
@if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
@endif
<table class="table table-bordered">
<tr>
<th>No</th>
<th>Name</th>
<th>Details</th>
<th width="280px">Action</th>
</tr>
@foreach ($products as $product)
<tr>
<td>{{ ++$i }}</td>
<td>{{ $product->name }}</td>
<td>{{ $product->detail }}</td>
<td>
<form action="{{ route('products.destroy',$product->id) }}" method="POST">
<a class="btn btn-info" href="{{ route('products.show',$product->id) }}">Show</a>
<a class="btn btn-primary" href="{{ route('products.edit',$product->id) }}">Edit</a>
@csrf
@method('DELETE')
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
@endforeach
</table>
{!! $products->links() !!}
@endsection
resources/views/products/create.blade.php
@extends('products.layout')
@section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Add New Product</h2>
</div>
<div class="pull-right">
<a class="btn btn-primary" href="{{ route('products.index') }}"> Back</a>
</div>
</div>
</div>
@if ($errors->any())
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<form action="{{ route('products.store') }}" method="POST">
@csrf
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Name:</strong>
<input type="text" name="name" class="form-control" placeholder="Name">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Detail:</strong>
<textarea class="form-control" style="height:150px" name="detail" placeholder="Detail"></textarea>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
@endsection
resources/views/products/edit.blade.php
@extends('products.layout')
@section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Edit Product</h2>
</div>
<div class="pull-right">
<a class="btn btn-primary" href="{{ route('products.index') }}"> Back</a>
</div>
</div>
</div>
@if ($errors->any())
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<form action="{{ route('products.update',$product->id) }}" method="POST">
@csrf
@method('PUT')
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Name:</strong>
<input type="text" name="name" value="{{ $product->name }}" class="form-control" placeholder="Name">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Detail:</strong>
<textarea class="form-control" style="height:150px" name="detail" placeholder="Detail">{{ $product->detail }}</textarea>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
@endsection
resources/views/products/show.blade.php
@extends('products.layout')
@section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2> Show Product</h2>
</div>
<div class="pull-right">
<a class="btn btn-primary" href="{{ route('products.index') }}"> Back</a>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Name:</strong>
{{ $product->name }}
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Details:</strong>
{{ $product->detail }}
</div>
</div>
</div>
@endsection
You can use Bootstrap 4 to style these views and make them look presentable.
You should also consider adding validation to the form data to ensure that the user enters valid data. You can use Laravel’s built-in validation features to accomplish this.
Once you have created the views and added validation, you should be able to test your CRUD application by running the development server and visiting the relevant routes in your web browser. You should be able to create new products, view a list of existing products, view the details of a specific product, update and delete products.
This concludes the tutorial on how to create a CRUD application in Laravel 8. You have learned how to install Laravel 8, configure the database, create migration, add resource route, create controller and model and create views for CRUD operations. This tutorial provided a basic example for beginners to understand and build their own CRUD application in Laravel 8.