Home > Blockchain >  Laravel 9 pass model object into view
Laravel 9 pass model object into view

Time:09-09

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>

CodePudding user response:

You can also send data to view like this: In controller: return view('play_quiz', $result); In view

foreach($quiz_tags as quiz){
//code
}

CodePudding user response:

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);
}
  • Related