Search code examples
laravelview

Laravel 9 pass model object into view


I am trying to pass a model object into view and use it in JS, but I can't make it work. It looks broken and throws a syntax error Uncaught SyntaxError: Unexpected token '&' if I just use the variable.

I tried using compact() but this does not work aswell compact(): Argument #1 must be string or array of strings, App\Models\Quiz given

Here is how I return the view with the object:

$result = Quiz::where('id', $quiz_id)->first();

if (!$result['active'] || $result['hidden_by_admin']) {
    return abort(404);
}
$result['classic_questions'] = ClassicQuestion::where('quiz_id', $quiz_id)->with('classic_answers')->get();
$result['quiz_tags'] = QuizHasTags::where('quizzes_id', $quiz_id)->with('quiz_tag')->get();

return view('play_quiz')->with('quiz', $result);

Here is how I want to access it in blade.php:

<script>
    const quiz = {{ $quiz }};
    console_log(quiz);
</script>

Solution

  • Assign your data into the window global object which will make it available everywhere and you can access it from your JS file:

    <ul>
        @foreach ($quiz as $quiz_data)
            <li> {{ $quiz_data }} </li>
        @endforeach
    </ul>
    <script type="text/javascript">
        window.data = {!! json_encode($quiz) !!};
    </script>
    <script src="...."></script>
    

    // trying to access the model $data from the view.

    $(function() {
        var values = window.data;
        alert(values);
    }