In the fast-paced world of web development, building robust and efficient data management systems is crucial. Being a PHP developer, I've found Laravel to be one of the most popular frameworks, loved for its elegance, simplicity, and ability to streamline the development process.
Recently, I discovered Livewire, a powerful full-stack framework for Laravel, which allows me to create dynamic, interactive user interfaces without the need for complex JavaScript code.
Throughout this article, I will take you on a journey to build a complete CRUD (Create, Read, Update, Delete) application in Laravel 10 using Livewire. CRUD operations are the backbone of most web applications, and mastering them is essential to managing data effectively, from creating new records to viewing, updating, and deleting existing ones.
The best part is, by harnessing the power of Livewire, I can create seamless and real-time data manipulation interfaces while still enjoying the benefits of Laravel's Blade syntax and robust PHP capabilities.
Together, we'll set up your Laravel project, create a Livewire component to handle the CRUD operations, design the user interface, set up the database, and implement the necessary logic for data manipulation.
Whether you're a seasoned Laravel developer looking to enhance your skills or a newcomer seeking a comprehensive guide to building dynamic web applications, this tutorial is for you. I'll equip you with the knowledge to create feature-rich CRUD operations in Laravel 10 with Livewire.
So, let's dive into the world of Laravel and Livewire as we embark on our journey to build a versatile CRUD application that's both intuitive and user-friendly and see laravel 10 Livewire crud operation, crud operation in laravel livewire, laravel 10 crud operation.
Ensure you have a Laravel 10 project set up and ready for Livewire CRUD operation. If you haven't created a Laravel project yet, you can use the following command to create one.
composer create-project --prefer-dist laravel/laravel laravel_10_livewire_crud
Then, we will install Livewire using the following composer command.
composer require livewire/livewire
Next, we need a database table to store our post items. Create a migration using the following command.
php artisan make:migration create_posts_table
Migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up(): void
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('description');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down(): void
{
Schema::dropIfExists('posts');
}
};
After that, we will migrate the table into the database using the following command.
php artisan migrate
Then, we will create Post Model using the below command.
php artisan make:model Post
App/Models/Post.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'title', 'description'
];
}
Then, we need to create a Livewire component that will handle the CRUD operations. In your terminal, run the following command to generate a new Livewire component.
php artisan make:livewire posts
This will create a new Livewire component named Posts
under the app/Http/Livewire
directory.
Open the app/Http/Livewire/Posts.php
file and define the view for the Livewire component. Replace the contents of the file with the following.
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\Post;
class Posts extends Component
{
public $posts, $title, $description, $post_id;
public $updateMode = false;
/**
* The attributes that are mass assignable.
*
* @var array
*/
public function render()
{
$this->posts = Post::latest()->get();
return view('livewire.posts');
}
/**
* The attributes that are mass assignable.
*
* @var array
*/
private function resetInputFields(){
$this->title = '';
$this->description = '';
}
/**
* The attributes that are mass assignable.
*
* @var array
*/
public function store()
{
$validatedDate = $this->validate([
'title' => 'required',
'description' => 'required',
]);
Post::create($validatedDate);
session()->flash('message', 'Post Created Successfully.');
$this->resetInputFields();
}
/**
* The attributes that are mass assignable.
*
* @var array
*/
public function edit($id)
{
$post = Post::findOrFail($id);
$this->post_id = $id;
$this->title = $post->title;
$this->description = $post->description;
$this->updateMode = true;
}
/**
* The attributes that are mass assignable.
*
* @var array
*/
public function cancel()
{
$this->updateMode = false;
$this->resetInputFields();
}
/**
* The attributes that are mass assignable.
*
* @var array
*/
public function update()
{
$validatedDate = $this->validate([
'title' => 'required',
'description' => 'required',
]);
$post = Post::find($this->post_id);
$post->update([
'title' => $this->title,
'description' => $this->description,
]);
$this->updateMode = false;
session()->flash('message', 'Post Updated Successfully.');
$this->resetInputFields();
}
/**
* The attributes that are mass assignable.
*
* @var array
*/
public function delete($id)
{
Post::find($id)->delete();
session()->flash('message', 'Post Deleted Successfully.');
}
}
Next, update the corresponding Blade view for the Livewire component. Create a new file named posts.blade.php
inside the resources/views/livewire
directory. In this view, we'll design the interface for the CRUD operations.
<div>
@if (session()->has('message'))
<div class="alert alert-success">
{{ session('message') }}
</div>
@endif
@if($updateMode)
@include('livewire.update')
@else
@include('livewire.create')
@endif
<table class="table table-bordered mt-5">
<thead>
<tr>
<th>No.</th>
<th>Title</th>
<th>Description</th>
<th width="150px">Action</th>
</tr>
</thead>
<tbody>
@foreach($posts as $post)
<tr>
<td>{{ $post->id }}</td>
<td>{{ $post->title }}</td>
<td>{{ $post->description }}</td>
<td>
<button wire:click="edit({{ $post->id }})" class="btn btn-primary btn-sm">Edit</button>
<button wire:click="delete({{ $post->id }})" class="btn btn-danger btn-sm">Delete</button>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
resources/views/livewire/create.blade.php
<form>
<div class="form-group">
<label for="exampleFormControlInput1">Title:</label>
<input type="text" class="form-control" id="exampleFormControlInput1" placeholder="Enter Title" wire:model="title">
@error('title') <span class="text-danger">{{ $message }}</span>@enderror
</div>
<div class="form-group">
<label for="exampleFormControlInput2">Description:</label>
<textarea class="form-control" id="exampleFormControlInput2" wire:model="description" placeholder="Enter Description"></textarea>
@error('description') <span class="text-danger">{{ $message }}</span>@enderror
</div>
<button wire:click.prevent="store()" class="btn btn-success">Save</button>
</form>
resources/views/livewire/update.blade.php
<form>
<input type="hidden" wire:model="post_id">
<div class="form-group">
<label for="exampleFormControlInput1">Title:</label>
<input type="text" class="form-control" id="exampleFormControlInput1" placeholder="Enter Title" wire:model="title">
@error('title') <span class="text-danger">{{ $message }}</span>@enderror
</div>
<div class="form-group">
<label for="exampleFormControlInput2">Description:</label>
<textarea class="form-control" id="exampleFormControlInput2" wire:model="description" placeholder="Enter Description"></textarea>
@error('description') <span class="text-danger">{{ $message }}</span>@enderror
</div>
<button wire:click.prevent="update()" class="btn btn-dark">Update</button>
<button wire:click.prevent="cancel()" class="btn btn-danger">Cancel</button>
</form>
Finally, include the Livewire assets in your main Blade layout file. Typically, this is the resources/views/welcome.blade.php
file.
resources/views/welcome.blade.php
<!DOCTYPE html>
<html>
<head>
<title> How To Create CRUD Operation In Laravel 10 Livewire - Vidvatek</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
@livewireStyles
</head>
<body>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">
<h2>How To Create CRUD Operation In Laravel 10 Livewire - Vidvatek</h2>
</div>
<div class="card-body">
@if (session()->has('message'))
<div class="alert alert-success">
{{ session('message') }}
</div>
@endif
@livewire('posts')
</div>
</div>
</div>
</div>
</div>
@livewireScripts
</body>
</html>
In order to use the Posts
, we need to register it in the Laravel application. Open the routes/web.php
file and add the following line.
// routes/web.php
use App\Http\Livewire\Posts;
Route::get('/posts', Posts::class);
Now, we will run the laravel 10 livewire crud operation using the following command.
php artisan serve
Congratulations! You have now successfully completed our comprehensive guide on building CRUD operations in Laravel 10 with Livewire. Throughout this journey, we explored the power and flexibility of Laravel combined with the real-time interactivity provided by Livewire, enabling us to create dynamic web applications with ease.
By now, you have gained a deep understanding of how to set up a Laravel project, integrate Livewire, and create a Livewire component to handle the full range of CRUD functionalities. With these skills in your toolkit, you are now equipped to develop robust data management systems for a wide range of web applications.
Thank you for joining me on this learning adventure. I hope this guide has been a valuable resource in your quest to become a proficient Laravel developer. Embrace the joy of coding, and never stop exploring new horizons in web development.
Happy coding!
You might also like:
- Read Also: Laravel 10 REST API CRUD Operation
- Read Also: Laravel 10 Import and Export CSV and Excel Files
- Read Also: Building Complete CRUD Application in Laravel 10
- Read Also: AJAX CRUD Operations In Laravel 10: Step-by-Step Guide