How to pass data to view in Laravel?
Asked Answered
B

16

93

Im passing data to my blade view with return View::make('blog', $posts); and in my blade view I'm trying to run an @foreach ($posts as $post) I end up with an error saying that $posts isn't defined.

My question is how would the $posts array be called?

Brycebryn answered 20/8, 2013 at 17:51 Comment(3)
return View::make('blog',compact('posts'));Decennium
To be clear, the 2nd parameter needs to be an associative array: array('posts' => $posts), or you can use the with() method as shown in the accepted answer.Stockjobber
return view('blog',compact('posts'));Overreach
B
114

You can pass data to the view using the with method.

return View::make('blog')->with('posts', $posts);
Boadicea answered 20/8, 2013 at 17:53 Comment(3)
How to pass collection ?Knucklebone
How to get it on view?Ornament
@MadhuramanGhimire write @foreach($posts as $post){ {{$post->title}} {{$post->author}} } or any other data that you need in the view.Neogothic
D
88

As of Laravel 5, the View::make() facade method from the 2013 accepted answer has been deprecated. Passing data to the view is now done using the view() helper function like this:

return view("blog", ["posts"=>$posts]);

Or, the same thing:

return view("blog", compact("posts"));

This can be combined with the with() method if desired:

return view("blog", compact("posts"))->with("message", "Comment posted");

Documentation is available here.

Denney answered 1/6, 2016 at 4:49 Comment(3)
True, but I still use with() to send bootstrap flash error/success messages to the view. Don't know how that could be done with compact().Neogothic
@Don'tDownvoteMe you can use the two together. return view("blog", compact("posts"))->with("success", "Hooray!");Denney
@Denney Thx Mike, never knew we could use with() along with compact().Neogothic
F
23

If you want to pass just one variable to view, you may use

In Controller

return view('blog')->withTitle('Laravel Magic method.');

In view

<div>
  Post title is {{$title}}.
</div>

If you want to pass multiple variables to view, you may use

In Controller

return view('blog')->withTitle('Laravel magic method')->withAuthor('Mister Tandon');

In view

<div>
   Post title is {{$title}}.Author Name is {{$author}}
</div>
Fiveandten answered 24/1, 2017 at 4:46 Comment(1)
Thanks for also showing how to use the variable in the blade template. That's the part I was missing.Indianapolis
F
14

You can also pass an array as the second argument after the view template name, instead of stringing together a bunch of ->with() methods.

return View::make('blog', array('posts' => $posts));

Or, if you're using PHP 5.4 or better you can use the much nicer "short" array syntax:

return View::make('blog', ['posts' => $posts]);

This is useful if you want to compute the array elsewhere. For instance if you have a bunch of variables that every controller needs to pass to the view, and you want to combine this with an array of variables that is unique to each particular controller (using array_merge, for instance), you might compute $variables (which contains an array!):

return View::make('blog', $variables);

(I did this off the top of my head: let me know if a syntax error slipped in...)

Falsecard answered 21/5, 2014 at 15:45 Comment(2)
please clarify my concept!! array('posts' => $posts) i have never seen this kind of Array is this an anonymous Array??? where is its name ?? All i know is that this array has key value pairAssentation
You can call it an anonymous array. So in that case when 'posts' array is passed to the view the key will be used as the name to access the $posts which are there inside the array.Pricillaprick
F
9

Tips1:

Using With(), This is a best practice

return view('about')->withName('Author Willson')->withJob('Writer');
return View::make('home')->with(compact('about'))
return View::make('home')->with('comments', $comments);

Tips2:

Using compact()

return view(about, compact('post1','post2'));

Tips3:

Using Second Parameters:

return view("about", ["comments"=>$posts]);
Finstad answered 27/6, 2018 at 6:14 Comment(1)
Why best practice tips1? Can't we use type2 directly.Allonym
C
7

controller:

use App\your_model_name;
funtion index()
{
$post = your_model_name::all();
return view('index')->with('this_will_be_used_as_variable_in_views',$post);
}

index:

<h1> posts</h1>
@if(count($this_will_be_used_as_variable_in_views)>0)
@foreach($this_will_be_used_as_variable_in_views as $any_variable)
<ul>
<p> {{$any_variable->enter_table_field}} </p>
 <p> {{$any_variable->created_at}} </p>
</ul>

@endforeach
@else
<p> empty </p>
@endif

Hope this helps! :)

Currey answered 7/11, 2017 at 10:21 Comment(0)
O
6
use TCG\Voyager\Models\Jobtype;

class FormController extends Controller
{
public function index()
{
   $category = Jobtype::all();
   return view('contact', compact('category'));

}
}
  • use your model
  • assign it to a variabel
  • pass the object to the view Here is an example:
October answered 10/7, 2017 at 6:1 Comment(0)
C
5

You can also do like this

$arr_view_data['var1'] = $value1;
$arr_view_data['var2'] = $value2;
$arr_view_data['var3'] = $value3;

return view('your_viewname_here',$arr_view_data);

And you access this variable to view as $var1,$var2,$var3

Chekiang answered 6/11, 2018 at 4:24 Comment(0)
D
4

You can also do the same thing in another way,

If you are using PHP 5.5 or latest one then you can do it as follow,

Controller:

return view(index, compact('data1','data2')); //as many as you want to pass

View:

<div>
    You can access {{$data1}}. [if it is variable]
</div>

@foreach($data1 as $d1)
    <div>
        You can access {{$d1}}. [if it is array]
    </div>
@endforeach

Same way you can access all variable that you have passed in compact function.

Hope it helps :)

Diastase answered 25/4, 2017 at 4:58 Comment(0)
H
2

You can pass data to the view using the with method.

return view('greeting', ['name' => 'James']);
Hardened answered 4/5, 2017 at 7:51 Comment(0)
P
2

You can pass your table data to view using compact.

$users = RoleModel::get();
 return view('super-admin',compact('users'));
Prevail answered 6/10, 2020 at 11:19 Comment(0)
A
1

You can also write for passing multiple data from your controller to a view

 return \View::make('myHome')
            ->with(compact('project'))
            ->with(['hello'=>$hello])
            ->with(['hello2'=>$hello2])
            ->with(['hello3'=>$hello3]);
Amphibiotic answered 21/2, 2018 at 6:44 Comment(0)
P
1

OK all the answers tell you how to pass data to the view but no one explains how to read it in the view .
if you use :

 //Routes/web.php
 ...
 Route::get('/user', function () {
    return view('profile', [
       'variable1' => 'value1' ,
       'variable2'=> 'value2' , // add as much as you want
    ]);
 });

To read these variables use in your views (in this example it's profile.blade.php file):

@if($variable1)

 <p> variable1 = {{  $variable1  }}</p>

@endif

Laravel does all the necessary work and creates $variable1 for you .

Piles answered 18/2, 2022 at 15:13 Comment(0)
A
0

For example, you have an array with your data.

$array1  =  $data;
$array2 = $data;

From your controller you can pass this variable using compact. You can pass as many array as you want.

return view('data.index',compact('array1','array2'));

Here data is a folder in view and index is the file with extension index.blade.php

In view you can call the arrays like this

@foreach ($array1 as $something)
   // some operation
@endforeach
Aalii answered 24/9, 2018 at 21:35 Comment(0)
A
0

Suppose if the variable name is $posts then we're passing an associative array where the key is posts and the value is the $posts array you want to pass.

return View::make('blog', ['posts' => $posts]);

Or we can use the with method to pass data.

return view('blog')->with('posts', $posts);

In your Blade view, you can access the $posts variable using Blade syntax like this:

@foreach ($posts as $post)
    {{-- Your code to display each post --}}
@endforeach
Atop answered 3/10, 2023 at 6:57 Comment(0)
H
-6

For any one thinking it is really tedious in the case where you have tons of variables to pass to a view or you want the variables to be accessible to many views at the same, here is another way

In the controller, you define the variables you want to pass as global and you attribute the values to these variables.

Example global $variable; $variable = 1;

And now in the view, at the top, simply do

<?php global $variable;?>

Then you can now call your variable from any where in the view for example

{{$variable}}

hope this helps someone.

Hoisch answered 16/10, 2018 at 10:24 Comment(2)
This is bad advice. You can easily pass data to a view in the controller why would you want to put it in global scope? @HoischBattlement
you might override one of laravel's global attributes and break everything apart !Piles

© 2022 - 2024 — McMap. All rights reserved.