Introduction
Welcome to Part 1 of our tutorial on creating the simplest CRUD (Create, Read, Update, Delete) application using Laravel. This tutorial is aimed at beginners and kids who are just starting to learn programming with PHP and Laravel. By the end of this tutorial series, you’ll have a basic CRUD application up and running.
Prerequisites
Before we start, make sure you have the following installed on your system:
- PHP (version 7.4 or later)
- Composer (dependency manager for PHP)
- Laravel Installer
- A database server (MySQL, SQLite, etc.)
If you haven’t installed Laravel yet, you can do so by running the following command in your terminal:
composer global require laravel/installer
Step 1: Setting Up a New Laravel Project
First, we need to create a new Laravel project. Open your terminal and run the following command:
laravel new simple_crud
This command will create a new Laravel project named simple_crud
.
Step 2: Configuring the Database
Laravel uses environment variables to configure various settings, including the database. Open the .env
file in the root directory of your project and update the database configuration:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=simple_crud
DB_USERNAME=root
DB_PASSWORD=
Make sure to replace DB_DATABASE
, DB_USERNAME
, and DB_PASSWORD
with your actual database name, username, and password.
Next, create the database in your database server. You can do this using a database management tool like phpMyAdmin or by running the following SQL command:
CREATE DATABASE simple_crud;
Step 3: Creating the Model and Migration
Now that our database is set up, let’s create a model and migration for our CRUD application. We’ll be creating a simple Item
model with the following attributes:
- id (integer, auto-increment)
- name (string)
- description (text)
- created_at (timestamp)
- updated_at (timestamp)
Run the following command to create the model and migration:
php artisan make:model Item -m
This command creates a model named Item
and a migration file. Open the migration file located in the database/migrations
directory and update it as follows:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateItemsTable extends Migration
{
public function up()
{
Schema::create('items', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('description');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('items');
}
}
Run the migration to create the items
table in the database:
php artisan migrate
Step 4: Creating the Controller
Next, we need a controller to handle the CRUD operations. Run the following command to create a controller named ItemController
:
php artisan make:controller ItemController
Open the newly created ItemController
located in the app/Http/Controllers
directory and update it as follows:
namespace App\Http\Controllers;
use App\Models\Item;
use Illuminate\Http\Request;
class ItemController extends Controller
{
public function index()
{
$items = Item::all();
return view('items.index', compact('items'));
}
public function create()
{
return view('items.create');
}
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'description' => 'required',
]);
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)
{
$request->validate([
'name' => 'required',
'description' => 'required',
]);
$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 5: Setting Up Routes
We need to define routes for our CRUD operations. Open the routes/web.php
file and add the following routes:
use App\Http\Controllers\ItemController;
Route::resource('items', ItemController::class);
This single line of code defines all the necessary routes for CRUD operations.
Step 6: Creating the Views
Finally, we need to create views for our CRUD operations. Create a new directory named items
in the resources/views
directory. Inside the items
directory, create the following view files:
index.blade.php
@extends('layouts.app')
@section('content')
<div class="container">
<h1>Items</h1>
<a href="{{ route('items.create') }}" class="btn btn-primary">Add Item</a>
@if ($message = Session::get('success'))
<div class="alert alert-success mt-3">
{{ $message }}
</div>
@endif
<table class="table mt-3">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@foreach ($items as $item)
<tr>
<td>{{ $item->id }}</td>
<td>{{ $item->name }}</td>
<td>{{ $item->description }}</td>
<td>
<a href="{{ route('items.show', $item->id) }}" class="btn btn-info">View</a>
<a href="{{ route('items.edit', $item->id) }}" class="btn btn-warning">Edit</a>
<form action="{{ route('items.destroy', $item->id) }}" method="POST" style="display:inline;">
@csrf
@method('DELETE')
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
@endsection
create.blade.php
@extends('layouts.app')
@section('content')
<div class="container">
<h1>Add 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" class="form-control" required>
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea name="description" class="form-control" required></textarea>
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
</div>
@endsection
show.blade.php
@extends('layouts.app')
@section('content')
<div class="container">
<h1>Item Details</h1>
<table class="table">
<tr>
<th>ID</th>
<td>{{ $item->id }}</td>
</tr>
<tr>
<th>Name</th>
<td>{{ $item->name }}</td>
</tr>
<tr>
<th>Description</th>
<td>{{ $item->description }}</td>
</tr>
</table>
<a href="{{ route('items.index') }}" class="btn btn-primary">Back to List</a>
</div>
@endsection
edit.blade.php
@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" class="form-control" value="{{ $item->name }}" required>
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea name="description" class="form-control" required>{{ $item->description }}</textarea>
</div>
<button type="submit" class="btn btn-primary">Update</button>
</form>
</div>
@endsection
Conclusion
In this first part of the tutorial, we’ve covered the basics of setting up a Laravel project, configuring the database, creating the model and migration, setting up the controller, defining routes, and creating views for the CRUD operations. In the next part, we’ll enhance the application by adding validation, improving the user interface, and handling errors gracefully.
Stay tuned for Part 2!