简体   繁体   中英

Pass Variable from Index View to Show View in Laravel 8 & Blade

Not sure what I'm missing, but I can't seem to get the variable from my index.blade.php view to my show.blade.php view.

I keep getting the error Undefined variable: usercar...

Livewire/Home/index.php

<?php

namespace App\Http\Livewire\Home;

use App\Models\User;
use App\Models\Car;
use App\Models\Usercar;
use Livewire\Component;
use Livewire\WithPagination;
use Illuminate\Database\Eloquent\Builder;

class Index extends Component
{
    use WithPagination;
    public $perPage = 25;
    public $sortAsc = true;
    public $search;

    protected $queryString = ['search'];

    public function render()
    {
        $usercars = Usercar::with('user')
            ->where('year', 'like', '%'.$this->search.'%')
            ->orwhereHas('user', function (Builder $query) {
                $query->where('first_name', 'like', '%'.$this->search.'%');
                $query->orWhere('last_name', 'like', '%'.$this->search.'%');
                $query->orWhere('drivers_number', 'like', '%'.$this->search.'%');
                $query->orwhereHas('region', function (Builder $query) {
                    $query->where('region_name', 'like', '%'.$this->search.'%');
                });
            })
            ->orwhereHas('car', function (Builder $query) {
                $query->where('model', 'like', '%'.$this->search.'%');
            })
            ->paginate($this->perPage);
        return view('livewire.home.index', compact('usercars'))
            ->layout('layouts.frontend');
    }
}

Livewire/Home/show.php

<?php

namespace App\Http\Livewire\Home;

use Livewire\Component;

class Show extends Component
{
    public function render()
    {
        return view('livewire.home.show')
            ->layout('layouts.frontend');
    }
}

livewire/home/index.blade.php

...
@foreach($usercars as $usercar)
...
<a href="{{route('home.show', $usercar->id)}}">View Car</a>
...
@endforeach
...

livewire/home/show.blade.php

...
<div>
    {{$usercar->car_color}}
</div>
...

web.php

...
Route::get('/', App\Http\Livewire\Home\Index::class)->name('home.index');
Route::get('/{usercar}', App\Http\Livewire\Home\Show::class)->name('home.show');
...

Of course you have to pass the url segment to the controller and the view:

<?php

namespace App\Http\Livewire\Home;

use Livewire\Component;

class Show extends Component
{
    public function render($usercar)
    {
        return view('livewire.home.show', [ 'usercar' => $usercar ])
            ->layout('layouts.frontend');
    }
}

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