Laravel Livewire Tutorial

Laravel-Livewire-Tutorial

Step 1:

Introduction to Laravel Livewire: 

Hello everyone and welcome to this Laravel Livewire tutorial. Today, we’re going to be diving into Laravel Livewire and understanding what it is and why it’s used.

Laravel Livewire is a library that allows you to build dynamic user interfaces with Laravel. It offers a simple and elegant way to handle interactions with your user interface without the need for any JavaScript. This makes it easier and faster to build dynamic web applications.

So why use Laravel Livewire? Laravel Livewire makes it easier to build dynamic web applications as it takes care of all the complexities of JavaScript and offers a simple and elegant solution. With Laravel Livewire, you can build dynamic interfaces with just a few lines of code, making it easier and faster to build complex applications.

In this tutorial, we’re going to be covering the basics of Laravel Livewire, and by the end, you will have a solid understanding of what it is and how it can be used to build dynamic web applications.

Let’s get started.”

Step 2:

Installation and setup

In this section, we’ll be covering the installation and setup of Laravel and creating a new project.

First, let’s make sure we have all the necessary requirements. You’ll need to have PHP and Composer installed on your system.

You can check if you have these by running the following commands in your terminal:

php -v
composer -v

Once you have these installed, we can start by creating a new Laravel project. To do this, we’ll use the following command:

composer create-project --prefer-dist laravel/laravel myproject

This will create a new Laravel project in a directory called myproject. You can replace myproject with your desired project name.

Next, we’ll need to navigate into our project directory and run the following command:

cd myproject

Now that we have our project set up, we can install Laravel Livewire. To do this, we’ll use the following command:

composer require livewire/livewire

This will install the latest version of Laravel Livewire into our project.

And that’s it! We’ve successfully installed Laravel and set up a new project with Laravel Livewire. In the next section, we’ll dive into the basics of Laravel Livewire and how it works.

Step 3:

Components

“In this section, we’re going to dive into the heart of Laravel Livewire and learn about components.

A component in Laravel Livewire is a reusable piece of UI that can be rendered on the page, and can also interact with the server.

Think of it as a custom HTML tag that you can use throughout your application.

Let’s start by creating a new component. To do this, we’ll run a command in our terminal:

php artisan make:livewire name-of-component

This will create two files for us: a Blade template and a PHP class.

In the Blade template, we can define the HTML for our component. For example:

<div>
<h1>{{ $title }}</h1>
<p>{{ $body }}</p>
</div>

In the PHP class, we can define the behavior and data for our component. For example:

class NameOfComponent extends Component
{
   public $title;
   public $body;

public function mount()
{
   $this->title = 'Hello, World!';
   $this->body = 'This is my first Laravel Livewire component.';
}
}

Now that we have a basic component set up, let’s use it in one of our views. To do this, we’ll use the livewire Blade directive:

home.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Livewire Tutorial For Beginners</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
@livewireStyles
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container-fluid">
<a class="navbar-brand" href="/">Livewire Basics</a>
</div>
</nav>
<div class="container">
<div class="row justify-content-center mt-3">
@livewire('mycomponent')
</div>
</div>
@livewireScripts
</body>
</html>

And that’s it! Our component is now rendered on the page. We can even interact with it in real-time by updating the data in the PHP class.

In the next section, we’ll learn how to pass data to components and interact with them using JavaScript events.

But for now, let’s celebrate the fact that we just created our first Laravel Livewire component!”

Step 4:

Data Binding

“In this section, we will dive into the powerful feature of Laravel Livewire – data binding. Data binding allows you to dynamically update the view without the need for a page refresh. We will start by creating a new component to showcase this feature.

First, we will create a new component using the Livewire CLI. In your terminal, run the following command:

php artisan make:livewire DataComponent

This will generate a new component file in the app/Http/Livewire directory. Open the file and let’s add a property to bind data to the view.

class DataComponent extends Component
{
   public $message;

public function render()
{
return view('livewire.data-component');
}
}

Next, we will create the view file for this component. Create a new file in the resources/views/livewire directory named data-component.blade.php.

<div>
<input type="text" wire:model="message">
<p>{{ $message }}</p>
</div>

In the view, we have added an input field with a wire:model directive. This directive binds the value of the input field to the $message property in our component.

As you type in the input field, the value of the $message property will be updated, and the view will dynamically update to show the new value.

Finally, let’s add the component to our application. Open your resources/views/home.blade.php file and add the following code:

<div class="container">
<data-component></data-component>
</div>

Step 5:

Event Handling

“In this section, we’ll look at how to handle events in Laravel Livewire. To get started, let’s create a simple form component that submits data to the server.

First, create a new component using the Artisan command:

php artisan make:livewire submitForm

Next, let’s update the submitForm.php file with the following code:

namespace App\Http\Livewire;

use Livewire\Component;

class SubmitForm extends Component
{
public $message;

public function render()
{
return view('livewire.submit-form');
}

public function submit()
{
$this->message = 'Form submitted successfully';
}
}

Here, we define a public property message that will be used to store the message displayed to the user after the form is submitted. The submit method is used to update the message when the form is submitted.

Next, let’s create the submit-form.blade.php file in the resources/views/livewire directory with the following code:

<div>
<form wire:submit.prevent="submit">
<input type="text" wire:model="message">

<button type="submit">Submit</button>
</form>

@if($message)
<p>{{ $message }}</p>
@endif
</div>

Here, we use the wire:submit.prevent directive to handle the form submission and trigger the submit method defined in the component. The wire:model directive is used to bind the input field to the message property.

Finally, let’s display the component in a view file. For example, you can add the following code to the home.blade.php file:

<div class="content">
<livewire:submit-form />
</div>

With this code, you should now be able to submit the form and see the message displayed on the screen. This demonstrates how to handle events such as form submissions in Laravel Livewire. With this basic understanding, you can start building more complex components and applications.”

Step 6:

AJAX in Laravel Livewire – Making Dynamic Requests

In this post, we will be discussing how to make AJAX requests from your components and how to update the view in response to a successful request.

Components:
Let’s start by creating a new component for demonstration purposes. In this example, we’ll create a simple form that allows the user to search for products.

First, let’s create a model for our products. Run the following command in your terminal:

php artisan make:model Product -m

Next, let’s create a database table for our products. In the create_products_table function in your database/migrations/[timestamp]_create_products_table.php file,

add the following code:

Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('description');
$table->integer('price');
$table->timestamps();
});

Now, let’s create a component for our search functionality. Run the following command in your terminal:

php artisan make:livewire ProductSearch

In the ProductSearch.php component, let’s add the following code to handle the search functionality:

class ProductSearch extends Component
{
public $search;

public function render()
{
$products = Product::where('name', 'like', "%{$this->search}%")->get();

return view('livewire.product-search', ['products' => $products]);
}

Finally, let’s make an AJAX request to retrieve the search results from the server. To do this, we will use the $refresh property of the component.

In the ProductSearch.php component, add the following code:

public function updatedSearch()
{
$this->emit('searchUpdated');
}

public function mount()
{
$this->search = request()->query('search', $this->search);
}

}

In the product-search.blade.php template, let’s add the following code to display the search results:

<div>
<input wire:model="search" type="text" placeholder="Search for products">
<br><br>
<table>
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Price</th>
</tr>
</thead>
<tbody>
@foreach ($products as $product)
<tr>
<td>{{ $product->name }}</td>
<td>{{ $product->description }}</td>
<td>{{ $product->price }}</td>
</tr>
@endforeach
</tbody>
</table>
</div>

<script>
document.addEventListener("input", function (event) {
if (event.target.matches('[wire\\:model]')) {
window.livewire.directive('refresh');
}
});
</script>

This code makes an AJAX request whenever the user types in the search field, and updates the view with the search results from the server.

Here is a basic code for the Product model in Laravel:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
protected $fillable = [
'name', 'description', 'price'
];
}

You can use Laravel’s database seeding feature to generate dummy data for the products table. Here’s how:

Create a seeder class using the following Artisan command:

php artisan make:seeder ProductsTableSeeder

In the ProductsTableSeeder class, add the following code to generate dummy data for the products table:

use Illuminate\Database\Seeder;
use App\Product;

class ProductsTableSeeder extends Seeder
{
public function run()
{
$products = [
[
'name' => 'Product 1',
'description' => 'This is a description for product 1',
'price' => 10.00
],
[
'name' => 'Product 2',
'description' => 'This is a description for product 2',
'price' => 20.00
],
[
'name' => 'Product 3',
'description' => 'This is a description for product 3',
'price' => 30.00
],
];

foreach ($products as $product) {
Product::create($product);
}
}
}

In the DatabaseSeeder class, call the ProductsTableSeeder class:

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
public function run()
{
$this->call(ProductsTableSeeder::class);
}
}

Finally, run the following Artisan command to seed the data into the products table:

php artisan db:seed

Step 7:

Dynamic Components

In this example, we will create a component to add and remove tasks. Start by creating a new component using the Artisan command:

php artisan make:livewire TaskList

In the TaskList.php file, add the following code:

<?php

namespace App\Http\Livewire;

use App\Models\Task;
use Livewire\Component;

class TaskList extends Component
{
public $newTask;

public function render()
{
return view('livewire.task-list', [
'tasks' => Task::all(),
'newTask' => $this->newTask
]);
}

public function addTask()
{
$task = new Task;
$task->task = $this->newTask;
$task->save();

$this->resetInput();
}

public function resetInput()
{
$this->newTask = '';
}

public function removeTask($id)
{
Task::destroy($id);
}
}

In the task-list.blade.php file, add the following code:

<div>
<input wire:model="newTask" type="text" placeholder="Add a new task">
<button wire:click="addTask">Add Task</button> <hr>

<style>
table {
width: 100%;
border-collapse: collapse;
}

th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}

th {
background-color: #ddd;
}

tr:nth-child(even) {
background-color: #f2f2f2;
}
</style>

<table>
<thead>
<tr>
<th>Task</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@foreach ($tasks as $task)
<tr>
<td>{{ $task->task }}</td>
<td>
<button wire:click="removeTask({{ $task->id }})" class="btn btn-danger">Delete</button>
</td>
</tr>
@endforeach
</tbody>
</table>

</div>

To create a database and models for a task list, follow these steps:

Set up a database:

Open your terminal and connect to your database

Run the following command to create a new database:

create database task_list;
php artisan make:model Task -m

The -m flag will also create a migration file for you.

Create a migration:

Open the newly created migration file located in database/migrations directory

Define the schema for your tasks table:

Schema::create('tasks', function (Blueprint $table) {
$table->id();
$table->string('task');
$table->timestamps();
});

Run the migrations:

Run the following command to run the migrations and create the tasks table:

php artisan migrate

Seed the database with sample data (optional):

Create a new seeder using the following command:

php artisan make:seeder TasksTableSeeder

Open the newly created seeder file located in the database/seeds directory and add some sample data:

public function run()
{
Task::create([
'task' => 'Clean the house'
]);
Task::create([
'task' => 'Wash the dishes'
]);
Task::create([
'task' => 'Take out the trash'
]);
}

Run the following command to seed the database with sample data:

php artisan db:seed --class=TasksTableSeeder

In your Task.php Model add:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Task extends Model
{
protected $fillable = ['task'];
}

To display the component in a view, use the following code:

@livewire('task-list') 

in home.blade.php

Step 8:

Server-side Validation: 

To perform server-side validation with Livewire, you need to first define a rules array in your Livewire component that specifies the validation rules

for each field you want to validate. You can then use Livewire’s built-in $this->validate method to perform the validation.

Here’s an example code for a Livewire component that performs server-side validation for a task:

Task.php

class TaskList extends Component
{
public $newTask;

public function render()
{
return view('livewire.task-list', [
'tasks' => Task::all(),
'newTask' => $this->newTask
]);
}

public function addTask()
{
$this->validate([
'newTask' => 'required|max:10'
]);

$task = new Task;
$task->task = $this->newTask;
$task->save();

$this->resetInput();
}

public function resetInput()
{
$this->newTask = '';
}

public function removeTask($id)
{
Task::destroy($id);
}
}

then in the tasklist.blade.php update the view file as follows:

task-list.blade.php

<div>
<input wire:model="newTask" type="text" placeholder="Add a new task">
<button wire:click="addTask">Add Task</button> <hr>

<div class="form-group">
@error('newTask')
<div class="alert alert-danger">{{ $message }}</div>
@enderror
</div>

<style>
table {
width: 100%;
border-collapse: collapse;
}

th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}

th {
background-color: #ddd;
}

tr:nth-child(even) {
background-color: #f2f2f2;
}
</style>

<table>
<thead>
<tr>
<th>Task</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@foreach ($tasks as $task)
<tr>
<td>{{ $task->task }}</td>
<td>
<button wire:click="removeTask({{ $task->id }})" class="btn btn-danger">Delete</button>
</td>
</tr>
@endforeach
</tbody>
</table>

</div>

 

Sign up for free tutorials in your inbox.

We don’t spam! Read our privacy policy for more info.

1 thought on “Laravel Livewire Tutorial”

  1. Pingback: Laravel Livewire 3 for Dynamic Web Development - Webdev Trainee

Leave a Comment

Your email address will not be published. Required fields are marked *