In this approachable lesson, we will learn how to create a straightforward CRUD (Create, Read, Update, Delete) application from scratch and go into the realm of Laravel, a PHP framework. The majority of online applications are built on the CRUD model, which makes it simple for users to interact with data. You’ll have a firm grasp of Laravel’s fundamental concepts by the end of this blog post and be able to easily develop your own CRUD application.
Step 1: Setup and Installation
Before we dive into the tutorial, make sure you have the following set up on your local machine
- PHP installed (version 7.4 or higher is recommended)
- Composer (PHP package manager)
- A web server (e.g., Apache or Nginx)
- Laravel installed (you can install it via Composer)
Assuming you have Laravel installed, open your terminal and create a new Laravel project using the following command:
composer create-project --prefer-dist laravel/laravel crud-app
This will create a new Laravel project named “crud-app” in a folder with the same name. Move into the project directory using cd crud-app
.
Step 2: Database Configuration
Next, configure your database credentials in the .env
file located at the root of your Laravel project. Update the following lines:
DB_CONNECTION=mysql
DB_HOST=your_database_host
DB_PORT=your_database_port
DB_DATABASE=your_database_name
DB_USERNAME=your_database_username
DB_PASSWORD=your_database_password
Step 3: Creating the Database Table
Let’s create a new migration to set up our database table. Run the following command in your terminal:
php artisan make:migration create_items_table --create=items
This will generate a new migration file in the database/migrations
folder. Open the file and define the table schema. For instance, let’s create an “items” table with an “id,” “name,” “description,” and “price” columns:
public function up()
{
Schema::create('items', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('description');
$table->decimal('price', 8, 2);
$table->timestamps();
});
}
Step 4: Running the Migration
Run the migration to create the “items” table in the database:
php artisan migrate
Step 5: Creating the Model
Next, let’s create a model for our “Item” table. Run the following command:
php artisan make:model Item
This will generate an “Item” model in the app
folder.
Step 6: Building the Routes
In Laravel, routes define how URLs should be handled. Open the routes/web.php
file and add the following routes:
use App\Http\Controllers\ItemController;
Route::get('/items', [ItemController::class, 'index'])->name('items.index');
Route::get('/items/create', [ItemController::class, 'create'])->name('items.create');
Route::post('/items', [ItemController::class, 'store'])->name('items.store');
Route::get('/items/{item}', [ItemController::class, 'show'])->name('items.show');
Route::get('/items/{item}/edit', [ItemController::class, 'edit'])->name('items.edit');
Route::put('/items/{item}', [ItemController::class, 'update'])->name('items.update');
Route::delete('/items/{item}', [ItemController::class, 'destroy'])->name('items.destroy');
Step 7: Creating the Controller
Now, we need a controller to handle the logic for our CRUD operations. Run the following command to generate the controller:
php artisan make:controller ItemController --resource
This will create an ItemController
with the necessary CRUD methods.
Step 8: Implementing the CRUD Methods
In the ItemController
file (app/Http/Controllers/ItemController.php
), implement the CRUD methods:
use App\Models\Item;
use Illuminate\Http\Request;
public function index()
{
$items = Item::all();
return view('items.index', compact('items'));
}
public function create()
{
return view('items.create');
}
public function store(Request $request)
{
Item::create($request->all());
return redirect()->route('items.index')->with('success', 'Item created successfully!');
}
public function show(Item $item)
{
return view('items.show', compact('item'));
}
public function edit(Item $item)
{
return view('items.edit', compact('item'));
}
public function update(Request $request, Item $item)
{
$item->update($request->all());
return redirect()->route('items.index')->with('success', 'Item updated successfully!');
}
public function destroy(Item $item)
{
$item->delete();
return redirect()->route('items.index')->with('success', 'Item deleted successfully!');
}
Step 9: Creating the Views
Create a view in the resources ‘app.blade.php’
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Laravel App</title>
<!-- Add your CSS stylesheets here, for example: -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<!-- Add your custom CSS file if you have one -->
<link rel="stylesheet" href="{{ asset('css/custom.css') }}">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container">
<a class="navbar-brand" href="{{ route('items.index') }}">My Laravel App</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="{{ route('items.index') }}">All Items</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ route('items.create') }}">Add Item</a>
</li>
</ul>
</div>
</div>
</nav>
<div class="container mt-4">
@yield('content')
</div>
<!-- Add your JavaScript libraries here, for example: -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.1/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<!-- Add your custom JS file if you have one -->
<script src="{{ asset('js/custom.js') }}"></script>
</body>
</html>
resources/views/items/index.blade.php
(Display all items):
@extends('layouts.app')
@section('content')
<div class="container">
<h1>All Items</h1>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Price</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@foreach($items as $item)
<tr>
<td>{{ $item->id }}</td>
<td>{{ $item->name }}</td>
<td>{{ $item->description }}</td>
<td>{{ $item->price }}</td>
<td>
<a href="{{ route('items.show', $item->id) }}" class="btn btn-primary">View</a>
<a href="{{ route('items.edit', $item->id) }}" class="btn btn-info">Edit</a>
<form action="{{ route('items.destroy', $item->id) }}" method="POST" style="display: inline-block;">
@csrf
@method('DELETE')
<button type="submit" class="btn btn-danger" onclick="return confirm('Are you sure?')">Delete</button>
</form>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
@endsection
resources/views/items/create.blade.php
(Form to create a new item):
@extends('layouts.app')
@section('content')
<div class="container">
<h1>Create New Item</h1>
<form action="{{ route('items.store') }}" method="POST">
@csrf
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" id="name" class="form-control" required>
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea name="description" id="description" class="form-control" rows="3" required></textarea>
</div>
<div class="form-group">
<label for="price">Price</label>
<input type="number" name="price" id="price" class="form-control" required>
</div>
<button type="submit" class="btn btn-primary">Create</button>
</form>
</div>
@endsection
resources/views/items/show.blade.php
(Show details of a single item):
@extends('layouts.app')
@section('content')
<div class="container">
<h1>Item Details</h1>
<p><strong>ID:</strong> {{ $item->id }}</p>
<p><strong>Name:</strong> {{ $item->name }}</p>
<p><strong>Description:</strong> {{ $item->description }}</p>
<p><strong>Price:</strong> {{ $item->price }}</p>
<a href="{{ route('items.edit', $item->id) }}" class="btn btn-info">Edit</a>
<form action="{{ route('items.destroy', $item->id) }}" method="POST" style="display: inline-block;">
@csrf
@method('DELETE')
<button type="submit" class="btn btn-danger" onclick="return confirm('Are you sure?')">Delete</button>
</form>
</div>
@endsection
resources/views/items/edit.blade.php
(Edit an existing item):
@extends('layouts.app')
@section('content')
<div class="container">
<h1>Edit Item</h1>
<form action="{{ route('items.update', $item->id) }}" method="POST">
@csrf
@method('PUT')
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" id="name" class="form-control" value="{{ $item->name }}" required>
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea name="description" id="description" class="form-control" rows="3" required>{{ $item->description }}</textarea>
</div>
<div class="form-group">
<label for="price">Price</label>
<input type="number" name="price" id="price" class="form-control" value="{{ $item->price }}" required>
</div>
<button type="submit" class="btn btn-primary">Update</button>
</form>
</div>
@endsection
Conclusion:
Congratulations! You’ve successfully built a basic CRUD application using Laravel. You’ve learned how to set up the database, create migrations, models, controllers, and views to perform CRUD operations. With this foundation, you can continue exploring Laravel’s vast capabilities and build more complex web applications. Happy coding! 😊
+ There are no comments
Add yours