Home > Back-end >  Laravel- How to "catch" a variable with Javascript passed to a blade.php view
Laravel- How to "catch" a variable with Javascript passed to a blade.php view

Time:01-04

so i'm currently working on a project and i want to add a calendar to one view, i'm using FullCalendar, the calendar is shown in the view but i'm currently trying to add events to that calendar, those events are going to be "pulled" from my database into the calendar to be displayed, now the problem is that when i pass the array with the events to the blade.php view that contains the calendar a error comes up saying that the variable "events" is undefined and i don't know if i'm doing something wrong, here's the code:

RegisteredUserController.php

$events = array();
        $citas = Cita::all();
        foreach($citas as $cita){
            $events[] = [
                'title' => $cita->paciente_id,
                'start' => $cita->hora_de_inicio,
                'end' => $cita->hora_de_finalizacion
            ];
        }

return redirect(RouteServiceProvider::HOME)->with(['events' => $events]);

RouteServiceProvider.php

public const HOME = '/home';

homeView.blade.php (This is where i get the error, in the line where i assign it to citas)

<div id="calendar">

    </div>

    <script>
        $(document).ready(function(){
            var citas = @json($events);
            $('#calendar').fullCalendar({
                header: {
                    left: 'month, agendaWeek, agendaDay',
                },
                events: citas
            })
        });
    </script>

routes / web.php

Route::get('/home', function (){
    return view('homeView');
})->name('homeView');

Not sure if it's helpful but i'm using Laravel's Breeze to handle the authentication of users, so when an user is aunthenticated they're redirected to the page where the calendar is.

i've tried the following

RegisteredUserController.php

return redirect(RouteServiceProvider::HOME, compact('events));

This one makes the whole calendar disappear:

homeView.blade.php

var citas = {{ Session::get('events') }};

Thank you in advance.

CodePudding user response:

the return should be like this

return view('path_of_the_blade', compact('events'));

So then in View, you can use

<script>
    var citas = @json($events);
</script>

CodePudding user response:

On you controller, why don't you just simply use:

return view('homeView')->with(['events' => $events]);

or simplier:

return view('homeView', compact('events'));

or even

return view('homeView', ['events']);

This would surely pass the variable events on the blade file.

Then on your blade file, you will just reference it as:

var citas = {{ $events }};
  • Related