简体   繁体   中英

Passing a value from one page to another in Laravel Livewire

I am quite new to Livewire Laravel and I have a small issue regarding how to pass a value from one page to another. I have two livewire components & blades (Booklist and Book) and a table rendered on the booklist like this:

 <table> <tr> <th>ID</th> <th>Name</th> <th>Author</th> <th>Action</th> </tr> <tr> <td>1</td> <td>Harry Potter</td> <td>JK Rowling</td> <td><button>Details</button></td> </tr> <tr> <td>2</td> <td>Percy Jackson</td> <td>Rick Riordan</td> <td><button>Details</button></td> </tr> <tr> <td>3</td> <td>Game of Thrones</td> <td>George R.R. Martin</td> <td><button>Details</button></td> </tr> </table>

The scenario is that when the user clicks the "details" button, it will move to the other page (Book) to show the full details of that book. Unfortunately it is unable to transfer at least the ID of that book. I've tried the $emit feature on the livewire however it does not work.

Component 1:

class Booklist extends Component
{
    public $data;
    public function render()
    {
        $this->data = Books::all();
        return view('livewire.bookstore.booklist');
    }

    public function getDetails($id){
        $this->emit('newPost', $id);
        return redirect()->to('bookstore/detail');
    }
}

Component 2:

class Book extends Component
{

    public $listeners = ['newPost'];
    public $numberid;
    public $data;

    public function render()
    {
        return view('livewire.bookstore.detail');
    }

    public function newPost($id){
        $this->numberid = $id->id;
    }

    public function checkifdata(){
        session()->flash('message','Number is ' . $this->numberid);
    }
}

If you are planing to have a different page for book details, then you can simply follow Full-Page Components rendering.

Route::get('/booklist', Booklist::class);
Route::get('/book/{$book}', Books::class);

Booklist Component

class Booklist extends Component
{
    public $books;

    public function mount()
    {
        $this->books = Books::all();
    }

    public function render()
    {
        return view('livewire.bookstore.booklist');
    }
}

On details click, Route Model Binding will take place.

@foreach($books as $book)
    <td><a href="{{ url('book/' . $book->id) }}">Details</a></td>
@endforeach

Book Component

class Book extends Component
{

    public $book;

    public function mount(Book $book)
    {
        $this->book = $book;
    }

    public function render()
    {
        return view('livewire.bookstore.detail');
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM