AP 2022
AP 2022

Reputation: 787

Check if resource exists before rendering full page component on Livewire

How can I check if resource exists prior to rendering full page component with Livewire? This is pretty simple with the Laravel Controller.

My route:

Route::get('/profiles/{id}', \App\Http\Livewire\Profiles\Manage::class)->name('profiles.manage');

I was the Profiles\Manage class to check whether profile exists or not before rendering the full page component.

I am mounting the profile data using the mount function within the component and trying to check if the profile exists or not (and redirect accordingly). However, the redirect doesn't work.

public function mount($id)
{

    $this->profile = Profile::where(['user_id' => Auth::user()->id, 'id' => $id])->first();
    if(!$this->profile) {
        return redirect()->to('/404');
    }

}

I've also tried doing this within the render() method where the component view is returned but that method requires a livewire component to be rendered.

Upvotes: 1

Views: 1580

Answers (2)

mohammad hossein goli
mohammad hossein goli

Reputation: 71

Try this:

if(!$this->profile) {
        abort(404);
    }

Or you can use this:

abort_if(!$this->profile, 404);

Upvotes: 0

As Qirel said, I think that $this->profile does exist with empty value, so maybe you could try with findOrFail in your mount method:

$this->profile = Profile::findOrFail($id);

Upvotes: 0

Related Questions