Passing request parameter to View - Laravel
13,929
Solution 1
You can use:
public function post ($id, $name)
{
return view('pages.blog.post', ['name' => $name, 'id' => $id]);
}
or even shorter:
public function post ($id, $name)
{
return view('pages.blog.post', compact('name', 'id'));
}
EDIT If you need to return it as JSON you can simply do:
public function post ($id, $name)
{
return view('pages.blog.post', ['json' => json_encode(compact('name', 'id'))]);
}
Solution 2
Would something like this work?
class BlogController extends Controller
{
//
public function post ($id, $name) {
//get id and name and pass it to the view
return view('pages.blog.post', ['name' => $name, 'id' => $id]);
}
}
Author by
moh_abk
Updated on June 23, 2022Comments
-
moh_abk almost 2 years
Is it possible to pass a
route
parameter to a controller to then pass to a view inlaravel
?Example;
I have the route below;
Route::get('post/{id}/{name}', 'BlogController@post')->name('blog-post');
I want to pass
{id}
and{name}
to my view so in my controllerclass BlogController extends Controller { // public function post () { //get id and name and pass it to the view return view('pages.blog.post'); } }
-
moh_abk over 8 yearsIn my view I can view echo out the data this way
{{$name}}
. How can I pass this toJavaScript
? Or applyjson_encode
to it -
Marcin Nabiałek over 8 yearsYou can simple pass it to JavaScript putting value for example
<script>var = {{$name}}</script>
or you can use<span id="name">{{$name}}</span>
and using JavaScript get value of element withid='name'
-
moh_abk over 8 yearsWhen I do
var = {{$name}}
I get an error thrown by my IDEexpression expected
.. Normally I would just do<?php echo $name ?>
for example but I'm usingblade
which doesnt support such -
Marcin Nabiałek over 8 years@moh.ABK Sorry of course it should be
<script>var name = '{{$name}}'</script>