Laravel 9 pass model object into view - laravel

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>

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

You can also send data to view like this:
In controller:
return view('play_quiz', $result);
In view
foreach($quiz_tags as quiz){
//code
}

Related

Undefined variable on Laravel

I´m a beginner starting with Laravel. I´m trying to show a question made on this website.
Here is the Controller page:
public function show($id)
{
//Use the model to get 1 record from the database
$question = $Question::findOrFail($id);
//show the view and pass the record to the view
return view('questions.show')->with('question', $question);
}
I have included at the top of the file:
use App\Question;
Here is my blade page:
#section('content')
<div class="container">
<h1> {{ $question->title }} </h1>
<p class="lead">
{{ $question->description }}
</p>
<hr />
</div>
#endsection
In the model I have not defined anything since I don´t need to specify any special rule. And finally here is the Route:
Route::resource('questions', 'QuestionController');
I got the error "ErrorException Undefined Variable: Question" and supposedly the error is on:
$question = $Question::findOrFail($id);
I´m looking forward to your observations.
Kind Regards.
You just need to change the controller section
public function show($id)
{
//Use the model to get 1 record from the database
$question = Question::findOrFail($id); // here is the error
//show the view and pass the record to the view
return view('questions.show')->with('question', $question);
}
Explanation:- You are going to use a variable $Question that is not defined. This is the basic PHP error, not the laravel issue.
However, You are using the "App\Question" model class not a sperate variable.

What is the correct way to bring data from the controller to the vue.js? Laravel-vue.js

I haven't really used this method before and I'm confused where I'm going wrong.
I set the data in the controller, I added the mycourses entry but it's not coming through, everything else is coming in fine
$data['user'] = Auth::user()->load('userType');
$data['courses'] = StudentSchedule::where('instructor_id',Auth::user()->id)
->with('course', 'package.packageCourses', 'user', 'location')->get();
$data['mycourses'] = Course::all();
$data['locations'] = Location::all();
return view('home', $data);
After this I go to the blade and add this
<script>
const user = {!! json_encode($user) !!};
const mycourses = {!! json_encode($mycourses) !!};
const courses = {!! json_encode($courses) !!};
const locations = {!! json_encode($locations) !!};
</script>
Then this goes to the .js, but whats happening there is that its calling the vue
In the vue file I add this to the data()
courses: [],
mycourses: [],
locations: [],
In the vue file I add this to the mounted
this.courses = courses;
this.mycourses = mycourses;
this.locations = locations;
And the mycourses is giving me this error
Error in mounted hook: "ReferenceError: mycourses is not defined"
ReferenceError: mycourses is not defined
I added mycourses after all the other ones were added before, I have everything the same as the courses one and I'm still getting this error. What am I missing?
I'm not sure if this will be helpful or not, meaning perhaps there is a reason this method won't work given your circumstances.
I've found this method of setting/passing data to be pretty helpful. It's less overhead to have to parse in your blade templates (or wherever needed).
Controller
public function myFunction() {
...
$user = Auth::user()->load('userType');
$courses = StudentSchedule::where('instructor_id', $user->id)->with('course', 'package.packageCourses', 'user', 'location')->get();
$mycourses = Course::all();
$locations = Location::all();
// Verify the data is correct.
// dd($courses);
return view('example', compact('user', 'courses', 'mycourses', 'locations');
}
You can verify each is returning the value needed by checking what it's returning using dd().
If you have a vue component you are passing data to that exists in your blade template, you could do something like this to pass the data in as props
example.blade.php
<p>Example content...</p>
<p>Hello, {{ $user->name }}</p>
<example-component :courses="courses" :mycourses="mycourses"></example-component>
<p>...</p>
Now we have passed courses and mycourses to the view component. You can access them there:
<script>
export default {
name: 'ExampleComponet',
data() {
return {
//
}
},
methods: {
//
},
props: {
courses: {
type: Object,
required: true
},
mycourses: {
type: Object,
required: true
},
},
}
</script>
You'll need to update the property type for each of the props you pass in. Perhaps courses isn't an object, but rather a string.
I'm not sure if I've exactly solved your issue, but hope this helps get you in the right direction.

URL::to('/') echoed as string (Laravel)

I'm working with my project which get new orders and append to DOM with jQuery.
jQuery
setInterval(function() {
$.ajax({
type:'POST',
url:'{{URL::to('/')}}/orders',
success:function(data)
{
let obj = JSON.parse(data)
let ordersDiv = $('#ordersDiv');
let queueCount = $('#queueCount');
queueCount.html(obj.count);
ordersDiv.html(obj.data);
}
});
}, 15000);
Controller
//some code here
$data .= "<a class=\"example-image-link\"
href=\"{{URL::to('/')}}/users/uploads/profiles/{{strlen($biker-
>picture_file_path)>0?$biker>picture_file_path:'avatar.png'}}\">
<img src=\"URL::to('/')/users/uploads/profiles/$biker-
>picture_file_path:.'avatar.png'\" data-toggle=\"tooltip\"
title=\"HiBes Biker\">
</a>";
//more code here
My problem is that I'm getting this result:
<a href=\"{URL::to('\/')}\/order-details\/3159\">Details<\/a>
I expect a result something like this:
<a href=\"http://127.0.0.1:8000/order-details\/3159\">Details<\/a>
The reason your URLs still contain the placeholders is you are building HTML in your controller, not your view.
Ideally, you should switch this logic into the view, where the {{ $var }} syntax will work.
Create a new blade file bikerimage.blade.php
#foreach($bikers as $biker)
<a class="example-image-link"
href="{{URL::to('/')}}/users/uploads/profiles/{{ $biker->picture_file_path ?: 'avatar.png' }}">
<img src="{{ URL::to('/')}}/users/uploads/profiles/{{ $biker->picture_file_path ?: 'avatar.png' }}"
data-toggle="tooltip"
title="HiBes Biker"
>
</a>
#endforeach
Then in your controller, you can do something like
//some code here
$data = view('partials/bikerimage.blade.php', ['bikers' => $bikers])->render();
return [
'html' => $data,
];
This means you can still return the data as part of an ajax call, without having to build HTML in your controller.

Post/Get Methode with href and list-group-iteam

I try to build a post/get method with an list group team / href. Here is my code...
#if(count($variableController) > 0)
<ul class="list-group">
#foreach($variableController as $variableView)
{{$variableView->heimmannschaft}}
#endforeach
</ul>
#endif
spielerAuswahl is my view. And after a click on the list-group-item I get to this view. But there I need the information from the list-group-item.
Route::post('/spielerAuswahl', function () {
return 123;
//var_dump($_POST)
});
What I have to do?
replcae post with get method like this:
Route::get('/spielerAuswahl', function () {
return 123;
//var_dump($_POST)
});
if you want to return spielerAuswahl as view
Route::get('/spielerAuswahl', function () {
return view('spielerAuswahl');
});
dont forget
spielerAuswahl.blade.php should be in reousrces/view directory
on the other hand if you want to send some data to view
change route to :
Route::get('/spielerAuswahl/{somevar}', function ($somevar) {
return view('spielerAuswahl',compact('somevar'));
});
and send data like this:
#if(count($variableController) > 0)
<ul class="list-group">
#foreach($variableController as $variableView)
{{$variableView->heimmannschaft}}
#endforeach
</ul>
#endif
it was get method
if you want to use post method your action method should be POST
one way is using <form action="" method="post">

How to add/include views in Laravel using Ajax

I'm bit stuck at a place. I've got some views of small HTML sections which when combined gives the complete HTML page. I'm trying to build a website builder with Jquery, where I'm having a drop event which adds those particular views:
For example I've got HTML for slideshow:
<div id="slideshow" data-nitsid="2">
<div class="revolution-slider">
<ul>
<!-- SLIDE -->
#foreach($contents->slider as $sliders)
<li data-transition="{{ $sliders->transition }}" data-slotamount="{{ $sliders->slotamount }}" data-masterspeed="{{ $sliders->masterspeed }}">
<!-- MAIN IMAGE -->
<img src="{{ URL::asset($sliders->url) }}" alt="">
</li>
#endforeach
</ul>
</div>
</div>
In my JQuery code:
nitsbuilder.dropeventhandler = function ($item, $position) {
var nits_id = $item.data('nitsid');
$.ajax({
method: 'POST',
url: dropurl,
data: { nits_id: nits_id, _token: token},
dataType: 'json',
success: function (data) {
nitsbuilder.adder($item, $position, data);
}
});
}
Before I was having html codes in the database so it was easier to pull out the html and add to the HTML page, now I'm having html in views, how can I push/include this HTML code or view to ajax request so that my nitsbuilder.adder function executes placing the view through my controller.
My present Controller is:
class DropeventController extends Controller
{
public function htmlcode(Request $request)
{
$pluginid = $request['nits_id'];
$code = Plugins::findOrFail($pluginid);
$htmlcode = $code->code;
return response()->json(['htmlcode' => $htmlcode]);
}
}
Please guide me. Thanks
You can easily create html strings from blade views using \View::make
e.g. let's assume you have the following folder strucutre
project
...
ressources
views
snippets
snippetA
snippetB
You could now create a route / controller accepting a "name" parameter and then do the following
$name = "snippetA"; // get this from parameters
$html = \View::make("snippets.$name")->render();
You might need to also add variables depending on your views
$name = "snippetA"; // get this from parameters
$errors = []; // error variable might be needed
$html = \View::make("snippets.$name", compact('errors'))->render();
You can then return this html string
return ['html' => $html];
And access it from your ajax done function.
I hope this helps
Suppose your html is in view file called abc.blade.php, you can return the rendered view from your controller in json.
return response()->json([
'htmlcode' => View::make('abc')->render();
]);

Resources