Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

brand87's avatar

A better way to pass this data to alpinejs?

Working on a slide/carousel sort of component for an app, this is how I currently pass the data through to the frontend but wondering if anyone can point out a better way?

$featuredProjects = Project::query()
            ->featured()
            ->limit(5)
            ->get();

        $featuredIds = $featuredProjects->pluck('id')->toArray();
        $featuredProjectsJson = $featuredProjects->toJson();

Then pass this data through to the new Laravel 7 component:

<x-featured-projects :projectIds="$featuredIds" :projects="$featuredProjectsJson" />

Then I use the ids to set the active project in alpine, is there possibly a way to do this without use two variables?

@props(['projectIds', 'projects'])

<div class=" max-w-4xl mx-auto" x-data="{ activeProject: {{ $projectIds[0] }}, projects: {{ $projects }} }" x-cloak>
    <template x-for="project in projects" :key="project.id">
        <div x-show="activeProject === project.id"
             class="bg-white rounded-lg shadow px-5 py-6 sm:px-6">
            <div x-text="project.title"></div>
        </div>
    </template>

    <div class="w-full flex items-center justify-center px-4">
        <template x-for="project in projects" :key="project.id">
            <button class="flex-1 w-4 h-2 mt-4 mx-2 mb-0 rounded-full overflow-hidden transition-colors duration-200 ease-out hover:bg-teal-600 hover:shadow-lg"
                :class="{ 'bg-orange-600': activeProject === project.id, 'bg-teal-300': activeProject !== project.id }"
                x-on:click="activeProject = project.id">
            </button>
        </template>
    </div>
</div>
0 likes
3 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

I don't really understand why you are passing in the ids? Do the following

activeProject: {{ json_decode($projects)[0]['id']}},

or just pass in the active ID

$featuredProjectsJson = $featuredProjects->toJson();
$activeProjectId = $featuredProjects->first()->id;

<x-featured-projects activeProject="$activeProjectId" :projects="$featuredProjectsJson" />


<div class=" max-w-4xl mx-auto" x-data="{ activeProject: {{ $activeProject }}, projects: {{ $projects }} }" x-cloak>
1 like
brand87's avatar

Thanks, I was passing the ids as was considering next/previous buttons and the ids won't always be consecutive but your code as shown me a way todo it without,

Thanks for that :)

estevao's avatar

A bit late for the discussion, but if anyone stumbles across this thread, theres now a more elegant solution:

 return {
    activeUf: 'go',
    map: null,
    markers: [],
    units: {{ Js::from($units) }}
};

This means that this function handles the array or collections parsing when you return data from your controller.

Hope it helps. Cheers.

Please or to participate in this conversation.