Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

How to use properties in Laravel livewire component

How public properties on component classes and can be accessed and modified on both the server and client-side.
How to initialize many properties using fill() method
How wire:model HTML attribute perform two way binding
How to reset your properties Using Reset method
Is reset() work on values set in mount()
What are Primitive types supports by laravel livewire
Difference between primitive data type and composite data type

How public properties on component classes and can be accessed and modified on both the server and client-side

you can set initial values for properties within your component's mount() method.

Consider the following example:

<?php

namespace App\Livewire;

use Illuminate\Support\Facades\Auth;
use Livewire\Component;

class TodoList extends Component
{
    public $todos = [];

    public $todo = '';

    public function mount()
    {
        $this->todos = Auth::user()->todos; 
    }

    // ...
}
Enter fullscreen mode Exit fullscreen mode

In this example, we've defined an empty todos array and initialized it with existing todos from the authenticated user. Now, when the component renders for the first time, all the existing todos in the database are shown to the user.

Crud example to explain how How public properties on component classes and can be accessed and modified on both the server and client-side

In Laravel Livewire, you can create a CRUD example where public properties in Livewire components can be accessed and modified on both the server and client-side. Below is a basic example to achieve this:

First, ensure you have Livewire installed in your Laravel application. If not, you can install it via Composer:

composer require livewire/livewire
Enter fullscreen mode Exit fullscreen mode

Next, let's create a Livewire component for our CRUD operations.

php artisan make:livewire TodoComponent
Enter fullscreen mode Exit fullscreen mode

Now, let's define the TodoComponent Livewire component and implement the CRUD operations inside it.

// app/Http/Livewire/TodoComponent.php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Todo; // Assuming you have a Todo model

class TodoComponent extends Component
{
    public $todos;
    public $task;

    public function mount()
    {
        $this->todos = Todo::all();
    }

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

    public function addTodo()
    {
        $this->validate(['task' => 'required']);
        $newTodo = Todo::create(['task' => $this->task]);
        $this->todos->push($newTodo);
        $this->task = '';
    }

    public function updateTodo($id, $task)
    {
        $todo = Todo::findOrFail($id);
        $todo->task = $task;
        $todo->save();
    }

    public function deleteTodo($id)
    {
        $todo = Todo::findOrFail($id);
        $todo->delete();
        $this->todos = $this->todos->filter(function ($todo) use ($id) {
            return $todo->id != $id;
        });
    }
}
Enter fullscreen mode Exit fullscreen mode

Now, let's create the corresponding Blade view file for our Livewire component:

<!-- resources/views/livewire/todo-component.blade.php -->

<div>
    <h1>Todo List</h1>
    <input type="text" wire:model="task">
    <button wire:click="addTodo">Add Todo</button>
    <ul>
        @foreach($todos as $todo)
            <li>
                <input type="text" wire:model="todos.{{ $loop->index }}.task" wire:change="updateTodo({{ $todo->id }}, $event.target.value)">
                <button wire:click="deleteTodo({{ $todo->id }})">Delete</button>
            </li>
        @endforeach
    </ul>
</div>
Enter fullscreen mode Exit fullscreen mode

Finally, include the Livewire component in your Blade view where you want to display the Todo list:

<!-- resources/views/welcome.blade.php -->

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Livewire Todo App</title>
    @livewireStyles
</head>
<body>
    @livewire('todo-component')
    @livewireScripts
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Make sure you have set up routes for Livewire components properly in your web.php file.

This example demonstrates how to create a basic Todo CRUD application using Laravel Livewire, where public properties like $todos and $task can be accessed and modified both on the server-side and client-side. Livewire handles the two-way data binding and updates the UI dynamically.

How to initialize many properties using fill() method

initializing many properties in the mount() method can feel verbose. To help with this, Livewire provides a convenient way to assign multiple properties at once via the fill() method. By passing an associative array of property names and their respective values, you can set several properties simultaneously and cut down on repetitive lines of code in mount()

<?php

namespace App\Livewire;

use Livewire\Component;
use App\Models\Post;

class UpdatePost extends Component
{
    public $post;

    public $title;

    public $description;

    public function mount(Post $post)
    {
        $this->post = $post;

        $this->fill( 
            $post->only('title', 'description'), 
        ); 
    }

    // ...
}
Enter fullscreen mode Exit fullscreen mode

How wire:model HTML attribute perform two way binding

Refrence
Livewire supports two-way data binding through the wire:model HTML attribute. This allows you to easily synchronize data between component properties and HTML inputs, keeping your user interface and component state in sync.

Let's use the wire:model directive to bind the $todo property in a TodoList component to a basic input element:

<?php

namespace App\Livewire;

use Livewire\Component;

class TodoList extends Component
{
    public $todos = [];

    public $todo = '';

    public function add()
    {
        $this->todos[] = $this->todo;

        $this->todo = '';
    }

    // ...
}
Enter fullscreen mode Exit fullscreen mode
<div>
    <input type="text" wire:model="todo" placeholder="Todo..."> 

    <button wire:click="add">Add Todo</button>

    <ul>
        @foreach ($todos as $todo)
            <li>{{ $todo }}</li>
        @endforeach
    </ul>
</div>
Enter fullscreen mode Exit fullscreen mode

In the above example, the text input's value will synchronize with the $todo property on the server when the "Add Todo" button is clicked.

How to reset your properties Using Reset method

Sometimes, you may need to reset your properties back to their initial state after an action is performed by the user. In these cases, Livewire provides a reset() method that accepts one or more property names and resets their values to their initial state.

In the example below, we can avoid code duplication by using $this->reset() to reset the todo field after the "Add Todo" button is clicked:

<?php

namespace App\Livewire;

use Livewire\Component;

class ManageTodos extends Component
{
    public $todos = [];

    public $todo = '';

    public function addTodo()
    {
        $this->todos[] = $this->todo;

        $this->reset('todo'); 
    }

    // ...
}
Enter fullscreen mode Exit fullscreen mode

In the above example, after a user clicks "Add Todo", the input field holding the todo that has just been added will clear, allowing the user to write a new todo.

What are Primitive types supports by laravel livewire

Livewire supports primitive types such as strings, integers, etc. These types can be easily converted to and from JSON, making them ideal for use as properties in Livewire components.

Livewire supports the following primitive property types: Array, String, Integer, Float, Boolean, and Null.

class TodoList extends Component
{
    public $todos = []; // Array

    public $todo = ''; // String

    public $maxTodos = 10; // Integer

    public $showTodos = false; // Boolean

    public $todoFilter; // Null
}

Enter fullscreen mode Exit fullscreen mode

Difference between primitive data type and composite data type

The terms "primitive data type" and "secondary data type" are not universally recognized in computer science terminology. However, I'll explain the difference between what I think you mean by "primitive" and "composite" or "derived" data types, which are more commonly used terms.

Primitive Data Types:

  1. Primitive data types are basic data types provided by a programming language that are directly supported by the language itself.
  2. They represent single values and are not composed of other values.
  3. Examples include integers, floating-point numbers, characters, booleans, etc.
  4. Primitive data types are typically used to represent simple values like numbers or characters
    .
    Composite or Derived Data Types:

  5. Composite or derived data types are data types that are constructed using primitive data types or other composite data types.

  6. They are composed of multiple elements and can represent complex structures.

  7. Examples include arrays, structures, classes, objects, etc.

  8. Composite data types are used to aggregate multiple values into a single entity, allowing for more complex data structures
    .
    Here's a more detailed explanation with examples:

Primitive Data Types:

Example: Integer
int x = 5;
Enter fullscreen mode Exit fullscreen mode

Composite or Derived Data Types:

Example: Array

int[] numbers = {1, 2, 3, 4, 5};
Enter fullscreen mode Exit fullscreen mode

In the above example, int is a primitive data type representing integers, while int[] is a composite data type representing an array of integers. The array data type is composed of multiple elements of the primitive data type int.

In summary, the key difference is that primitive data types represent single values, while composite data types represent collections of values or complex structures composed of other data types.

Example of setting properties as these various types

public function mount()
{
    $this->todos = collect([]); // Collection

    $this->todos = Todos::all(); // Eloquent Collection

    $this->todo = Todos::first(); // Model

    $this->date = new DateTime('now'); // DateTime

    $this->date = new Carbon('now'); // Carbon

    $this->todo = str(''); // Stringable
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)