Home > Mobile >  How to pass data from view to parent layout?
How to pass data from view to parent layout?

Time:05-28

Sorry that I need to paste so much code, but I assume this is necessary to understand my structure.

I have a users resource Route::resource('/clients', ClientController::class)->middleware(['auth']);

For the route users.show I have this function in my UsersController:

public function show(Client $client)
{
    return view('clients.show', [
        'client' => $client,
    ]);
}

Then I have my clients.show view simplified with

<x-client-layout>

    Bla Bla ...

</x-client-layout>

and I my layouts.client

@include('core.header')


    @include('layouts.navigation-client')

    <main >

        {{ $slot }}
        
    </main>

@include('core.footer')

Now for the layouts.navigation-client I want to create a link to the route Route('users.show', $client->id). But how can I pass the $client to the navigation view?

<x-nav-link :href="Route('users.show', $user->id)" :active="request()->routeIs('users.show')" icon="user">

What would work, but feels bad to do is:

Route('users.show', explode("clients/", url()->current())[1])

CodePudding user response:

In your users.show view you can pass the client id to the <x-client-layout>.

<!-- users.show view-->
<x-client-layout :client="$client">
    <!-- component markup -->
</x-client-layout>

Just make sure to define a default value for $client in the <x-client-layout /> component, say a Client with $client->id = 0, otherwise you may get an undefined error.

You can also conditionally display the link only when $client->id has a value other than 0 - that way you can set the default value to 0 and use the <x-client-layout /> for other views where you don't require the $client->id and there's no need to display the link.

Then you can pass the $client to the layouts.navigation-client and then use it for the <x-nav-link />

@props([
   'client'
])
@include('core.header')


    @include('layouts.navigation-client', ['client' => $client])

    <main >

        {{ $slot }}
        
    </main>

@include('core.footer')

And then in layouts.navigation-client

<x-nav-link :href="route('users.show', $client->id)" :active="request()->routeIs('users.show')" icon="user" />
  • Related