How to pass data to view in Laravel?

PhpLaravelPass DataLaravel Views

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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

return View::make('blog')->with('posts', $posts);

Solution 2 - Php

It's probably worth mentioning that as of Laravel 5, passing data to the view is now done like this:

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

Or:

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

Documentation is available here.

Solution 3 - Php

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>

Solution 4 - Php

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...)

Solution 5 - Php

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

Solution 6 - Php

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:

Solution 7 - Php

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! :)

Solution 8 - Php

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

Solution 9 - Php

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 :)

Solution 10 - Php

You can pass your table data to view using compact.

$users = RoleModel::get();
 return view('super-admin',compact('users'));

Solution 11 - Php

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

return view('greeting', ['name' => 'James']);

Solution 12 - Php

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

Solution 13 - Php

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 .

Solution 14 - Php

You can use the following to pass data to view in Laravel:

public function contact($id) {
    return view('contact',compact('id'));
}

Solution 15 - Php

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

Solution 16 - Php

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSam PetterssonView Question on Stackoverflow
Solution 1 - PhpMostafa ElgaafaryView Answer on Stackoverflow
Solution 2 - Phpmiken32View Answer on Stackoverflow
Solution 3 - PhpmistertandonView Answer on Stackoverflow
Solution 4 - PhpiconoclastView Answer on Stackoverflow
Solution 5 - PhpvenkatskpiView Answer on Stackoverflow
Solution 6 - Phpli bing zhaoView Answer on Stackoverflow
Solution 7 - PhpkamalView Answer on Stackoverflow
Solution 8 - PhpSagar jadhavView Answer on Stackoverflow
Solution 9 - PhpSagar NaliyaparaView Answer on Stackoverflow
Solution 10 - PhpAslam KhanView Answer on Stackoverflow
Solution 11 - PhpJay MomayaView Answer on Stackoverflow
Solution 12 - Phpuser9389401View Answer on Stackoverflow
Solution 13 - PhpYasser CHENIKView Answer on Stackoverflow
Solution 14 - PhpTheNameView Answer on Stackoverflow
Solution 15 - Phpuser3677355View Answer on Stackoverflow
Solution 16 - PhptkcView Answer on Stackoverflow