简体   繁体   中英

Can't display the values from my data base with Laravel Livewire

I'm using a Livewire component, this is my code:

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Recipe;
use App\Models\Vegetable;
use App\Models\VegetablesRecipe;


class Search extends Component
{
    public $query = '';
    public $vegetables;

    public function mount()
    {
        $this->resetQuery();
    }

    public function resetQuery()
    {
        $this->vegetables = [];
    }

    public function render()
    {
        if ($this->query != null) {
            return view('livewire.search', [
                'vegetables' => Vegetable::where('name', 'like', '%'.$this->query.'%')->get()->toArray()
            ]);
        } else {
            return view('livewire.search', [
                'vegetables' => Vegetable::all()->toArray()
            ]);
        }
    }
}

Because on the mount you are resetting the vegetable array to empty array

refer this fiddle for more details

https://laravelplayground.com/#/snippets/f51e212a-dab3-4325-b6b0-4c6af4c0ab72

Defining public $vegetables; will prevent you from passing it to the view. Remove that. Also remove your mounting logic.

Thus you should have:

class Search extends Component
{
    public $query = '';

    public function render()
    {
        if ($this->query != null) {
            return view('livewire.search', [
                'vegetables' => Vegetable::where('name', 'like', '%'.$this->query.'%')->get()->toArray()
            ]);
        } else {
            return view('livewire.search', [
                'vegetables' => Vegetable::all()->toArray()
            ]);
        }
    }
}

Also make sure you are calling @livewireScripts and @livewireStyles or their alternative syntaxes <livewire:styles /> <livewire:scripts /> from your main view which uses <livewire:search /> .

Edit:

Alternatively, you could also use a public properly and write to it using $this->vegetables like so:

class Search extends Component
{
    public $query = '';
    public $vegetables;

    public function render()
    {
            $this->vegetables = Vegetable::where('name', 'like', '%' . $this->query . '%')->get()->toArray();
            return view('livewire.search');
    }
}

Also, you can remove the @if(!empty($query))<\/code> and the @if(!empty($vegetables))<\/code> in place of a @forelse<\/code> utilising the @empty<\/code> statement rather than a @foreach<\/code> . Eg

@forelse($vegetables as $vegetable)
    <li><span class="material-icons">lunch_dining</span>{{ $vegetable['name'] }}</li>
@empty
    <li>No result</li>
@endforelse

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