To achieve this in a Laravel 11 application using Inertia.js and Vue 3, you need to ensure that the data layer event is pushed correctly when the specific action occurs. Here’s a step-by-step guide to help you set this up:
-
Create a Controller Method to Handle the Data Layer Event:
First, create a method in your controller that will handle the data layer event. This method will be responsible for returning the necessary data to your Vue component.
// app/Http/Controllers/DataLayerController.php namespace App\Http\Controllers; use Illuminate\Http\Request; use Inertia\Inertia; class DataLayerController extends Controller { public function viewItem() { $dataLayer = [ 'event' => 'view_item', 'ecommerce' => [ 'currency' => 'USD', 'value' => 30.03, 'items' => [ [ 'item_id' => 'SKU_12345', 'item_name' => 'Stan and Friends Tee', 'affiliation' => 'Google Merchandise Store', 'coupon' => 'SUMMER_FUN', 'discount' => 2.22, 'index' => 0, 'item_brand' => 'Google', 'item_category' => 'Apparel', 'item_category2' => 'Adult', 'item_category3' => 'Shirts', 'item_category4' => 'Crew', 'item_category5' => 'Short sleeve', 'item_list_id' => 'related_products', 'item_list_name' => 'Related Products', 'item_variant' => 'green', 'location_id' => 'ChIJIQBpAG2ahYAR_6128GcTUEo', 'price' => 10.01, 'quantity' => 3 ] ] ] ]; return Inertia::render('YourComponent', ['dataLayer' => $dataLayer]); } } -
Define a Route for the Controller Method:
Add a route in your
web.phpfile to handle the request to the controller method.// routes/web.php use App\Http\Controllers\DataLayerController; Route::get('/view-item', [DataLayerController::class, 'viewItem']); -
Update Your Vue Component to Push the Data Layer Event:
In your Vue component, use the
mountedlifecycle hook to push the data layer event when the component is mounted.<!-- resources/js/Pages/YourComponent.vue --> <template> <div> <!-- Your component template --> </div> </template> <script> export default { props: { dataLayer: Object }, mounted() { if (this.dataLayer) { window.dataLayer = window.dataLayer || []; window.dataLayer.push({ ecommerce: null }); // Clear the previous ecommerce object. window.dataLayer.push(this.dataLayer); } } } </script> -
Ensure Your Inertia Setup is Correct:
Make sure your Inertia setup is correctly configured to handle the data passed from the controller.
// resources/js/app.js import { createApp, h } from 'vue'; import { createInertiaApp } from '@inertiajs/inertia-vue3'; import { InertiaProgress } from '@inertiajs/progress'; createInertiaApp({ resolve: name => require(`./Pages/${name}`), setup({ el, App, props, plugin }) { createApp({ render: () => h(App, props) }) .use(plugin) .mount(el); }, }); InertiaProgress.init();
By following these steps, you should be able to push the specific data layer event using Laravel, Inertia.js, and Vue 3. This setup ensures that the data layer event is correctly pushed when the Vue component is mounted.