Laravel Livewire (1)

정종일·2023년 9월 15일
0

Laravel

목록 보기
1/9

Components

생성: php artisan make:livewire {{name}}

// app\Livewire\CreatePost.php

<?php
 
namespace App\Livewire;
 
use Livewire\Component;
 
class CreatePost extends Component
{
    public function render()
    {
        return view('livewire.create-post');
    }
}

// resources\views\livewire\create-post.blade.php

<div>
    {{-- ... --}}
</div>
  • 두 개의 파일 생성
  • render() 메서드는 livewire 컴포넌트 렌더 시 자동 호출
php artisan make:livewire Posts\\CreatePost
php artisan make:livewire posts.create-post

// 위 두 명령어로 sub-directories에 생성 가능

Inline components

php artisan make:livewire {{name}} --inline

namespace App\Livewire;
 
use Livewire\Component;
 
class CreatePost extends Component
{
    public function render()
    {
        return <<<'HTML' 
        <div>
            {{-- Your Blade template goes here... --}}
        </div>
        HTML;
    }
}
  • 인라인 태그 자동 생성도 가능

Omitting the render method

namespace App\Livewire;
 
use Livewire\Component;
 
class CreatePost extends Component
{
    //
}
  • render() 메서드는 생략이 가능하다

Setting properties

namespace App\Livewire;
 
use Livewire\Component;
 
class CreatePost extends Component
{
    public $title = 'Post title...';
 
    public function render()
    {
        return view('livewire.create-post');
    }
}
  • 컴포넌트 내부 프로퍼티에 대한 정의가 가능함

render

<div>
    <h1>Title: "{{ $title }}"</h1>
</div>

// "Post title..."

additional data

namespace App\Livewire;
 
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
 
class CreatePost extends Component
{
    public $title;
 
    public function render()
    {
        return view('livewire.create-post')->with([
            'author' => Auth::user()->name,
        ]);
    }
}

// 이런 식으로 값을 같이 넘겨주는 것도 가능하다

<div>
    <h1>Title: {{ $title }}</h1>
 
    <span>Author: {{ $author }}</span>
</div>

wire:key

<div>
    @foreach ($posts as $post)
        <div wire:key="{{ $post->id }}"> 
            <!-- ... -->
        </div>
    @endforeach
</div>
  • loop의 기준이 되는 키값을 지정 가능하다

Calling actions

namespace App\Livewire;
 
use Livewire\Component;
use App\Models\Post;
 
class CreatePost extends Component
{
    public $title;
 
    public function save() 
    {
        $post = Post::create([
            'title' => $this->title
        ]);
 
        return redirect()->to('/posts')
             ->with('status', 'Post created!');
    }
 
    public function render()
    {
        return view('livewire.create-post');
    }
}

------------------------------------------------

<form wire:submit="save"> 
    <label for="title">Title:</label>
 
    <input type="text" id="title" wire:model="title">
 
    <button type="submit">Save</button>
</form>
  • save 버튼 클릭 시 save() 메서드 호출 및 컴포넌트 re-render

Rendering components

<livewire:create-post />
  • 반드시 kebab-case 로 네이밍

Passing data into components

  • livewire 컴포넌트에 initial values를 넘기려면
    • <livewire:create-post title="Initial Title" />
  • 바인딩 되는 dynamic values를 넘기려면
    • <livewire:create-post :title="$initialTitle" />

데이터를 넘기면 컴포넌트의 mount() 메서드에서 해당 값을 받는다

namespace App\Livewire;
 
use Livewire\Component;
 
class CreatePost extends Component
{
    public $title;
 
    public function mount($title = null)
    {
        $this->title = $title;
    }
 
    // ...
}
  • mount() 는 생략 가능하다
  • 생략할 경우 livewire에서 매칭되는 이름으로 자동 매핑한다

Full-page components

use App\Livewire\CreatePost;
 
Route::get('/posts/create', CreatePost::class);
  • 바로 livewire 컴포넌트 라우팅도 가능하다

Layout files

  • full-page-components로 할 경우 어플리케이션 전체에 적용되는 layout이 필요하다
<!-- resources/views/components/layouts/app.blade.php -->
 
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
 
        <title>{{ $title ?? 'Page Title' }}</title>
    </head>
    <body>
        {{ $slot }}
    </body>
</html>

이 때, config/livewire.php 파일에서

'layout' => 'layouts.app',

해당 부분을 변경해 원하는 파일로 layout을 설정할 수 있다

Per-component layout configuration

namespace App\Livewire;
 
use Livewire\Attributes\Layout;
use Livewire\Component;
 
class CreatePost extends Component
{
    // ...
 
    #[Layout('layouts.app')] 
    public function render()
    {
        return view('livewire.create-post');
    }
}

--------------------------

public function render()
{
    return view('livewire.create-post')
         ->layout('layouts.app'); 
}

render 메서드 위에서 #[Layout('layouts.app')] 를 통해 커스텀 레이아웃 설정 가능

(클래스 위에 정의하거나 return시에 정의해줘도 된다)

Setting the page title

<head>
    <title>{{ $title ?? 'Page Title' }}</title>
</head>

---------------------------------

namespace App\Livewire;
 
use Livewire\Attributes\Title;
use Livewire\Component;
 
class CreatePost extends Component
{
    // ...
 
    #[Title('Create Post')] 
    public function render()
    {
        return view('livewire.create-post');
    }
}

// Null coalescing operator를 사용해 default 값 설정 가능
  • layout 설정과 동일하게 사용 가능

Accessing route parameters

route 파일 url에 정의된 파라미터 ({id})에 접근하기 위해서는 livewire 컴포넌트의 mount() 메서드 내에 파라미터를 받는 코드를 작성하면 된다

namespace App\Livewire;
 
use App\Models\Post;
use Livewire\Component;
 
class ShowPost extends Component
{
    public Post $post;
 
    public function mount($id) 
    {
        $this->post = Post::findOrFail($id);
    }
 
    public function render()
    {
        return view('livewire.show-post');
    }
}

------------------------------------------

<?php
 
namespace App\Livewire;
 
use App\Models\Post;
use Livewire\Component;
 
class ShowPost extends Component
{
    public Post $post;
 
    public function mount(Post $post) 
    {
        $this->post = $post;
    }
 
    public function render()
    {
        return view('livewire.show-post');
    }
}
profile
제어할 수 없는 것에 의지하지 말자

1개의 댓글

comment-user-thumbnail
2025년 3월 11일

This is a powerful feature, especially for applications with fast development requirements, but for projects that require high real-time features (like raft wars chat application or continuous data updates), it may be necessary to add technologies like Laravel Echo or use a specialized JavaScript solution for optimization.

답글 달기