Laravel - Pass more than one variable to view
Asked Answered
R

12

85

I have this site and one of its pages creates a simple list of people from the database. I need to add one specific person to a variable I can access.

How do I modify the return $view->with('persons', $persons); line to also pass the $ms variable to the view?

    function view($view)
    {
        $ms = Person::where('name', 'Foo Bar');

        $persons = Person::order_by('list_order', 'ASC')->get();

        return $view->with('persons', $persons);
    }
Robinia answered 21/11, 2013 at 1:31 Comment(0)
A
117

Just pass it as an array:

$data = [
    'name'  => 'Raphael',
    'age'   => 22,
    'email' => '[email protected]'
];

return View::make('user')->with($data);

Or chain them, like @Antonio mentioned.

Aleida answered 21/11, 2013 at 1:47 Comment(2)
The recommended way is to use compact method to pass variables. That feels rather more elegant.Byway
I think part of the choice would be based on the data. For a simple variable this works but with nested data with in a variable compact or with would work best for manipulating in the view.Gerik
D
109

This is how you do it:

function view($view)
{
    $ms = Person::where('name', '=', 'Foo Bar')->first();

    $persons = Person::order_by('list_order', 'ASC')->get();

    return $view->with('persons', $persons)->with('ms', $ms);
}

You can also use compact():

function view($view)
{
    $ms = Person::where('name', '=', 'Foo Bar')->first();

    $persons = Person::order_by('list_order', 'ASC')->get();

    return $view->with(compact('persons', 'ms'));
}

Or do it in one line:

function view($view)
{
    return $view
            ->with('ms', Person::where('name', '=', 'Foo Bar')->first())
            ->with('persons', Person::order_by('list_order', 'ASC')->get());
}

Or even send it as an array:

function view($view)
{
    $ms = Person::where('name', '=', 'Foo Bar')->first();

    $persons = Person::order_by('list_order', 'ASC')->get();

    return $view->with('data', ['ms' => $ms, 'persons' => $persons]));
}

But, in this case, you would have to access them this way:

{{ $data['ms'] }}
Deming answered 21/11, 2013 at 1:44 Comment(6)
Yep, I got this far in the mean time. But now when I try access it in the view e.g. {{ $ms->name }} I get Undefined property: Laravel\Database\Eloquent\Query::$name What am I missing?Robinia
You're missing the ->first() on the first line of your method.Aleida
pjmil116 just edited to add the ->first() Raphael was commenting about.Deming
Ah yep got it. I just realised this project is laravel 3 and thus a huge source of my frustration. Had to change the query syntax to $ms = DB::first('select * from people where name = "Foo Bar"');Robinia
Laravel 4 and 3 syntax, for common things like this, are pretty much the same. You can still use Person::where('name', '=', 'Foo Bar')->first(). Edited.Deming
How i can access this data in view? please guide mePheon
C
34

Use compact

function view($view)
{
    $ms = Person::where('name', '=', 'Foo Bar')->first();

    $persons = Person::order_by('list_order', 'ASC')->get();
    return View::make('users', compact('ms','persons'));
}
Christner answered 6/6, 2014 at 15:38 Comment(0)
G
23

Passing multiple variables to a Laravel view

//Passing variable to view using compact method    
$var1=value1;
$var2=value2;
$var3=value3;
return view('viewName', compact('var1','var2','var3'));

//Passing variable to view using with Method
return view('viewName')->with(['var1'=>value1,'var2'=>value2,'var3'=>'value3']);

//Passing variable to view using Associative Array
return view('viewName', ['var1'=>value1,'var2'=>value2,'var3'=>value3]);

Read here about Passing Data to Views in Laravel

Gerta answered 20/3, 2016 at 14:1 Comment(0)
O
5

This Answer seems to be

bit helpful while declaring the large numbe of variable in the function

Laravel 5.7.*

For Example

public function index()
{
    $activePost = Post::where('status','=','active')->get()->count();

    $inActivePost = Post::where('status','=','inactive')->get()->count();

    $yesterdayPostActive = Post::whereDate('created_at', Carbon::now()->addDay(-1))->get()->count();

    $todayPostActive = Post::whereDate('created_at', Carbon::now()->addDay(0))->get()->count();

    return view('dashboard.index')->with('activePost',$activePost)->with('inActivePost',$inActivePost )->with('yesterdayPostActive',$yesterdayPostActive )->with('todayPostActive',$todayPostActive );
}

When you see the last line of the returns it not looking good

When You Project is Getting Larger its not good

So

public function index()
    {
        $activePost = Post::where('status','=','active')->get()->count();

        $inActivePost = Post::where('status','=','inactive')->get()->count();

        $yesterdayPostActive = Post::whereDate('created_at', Carbon::now()->addDay(-1))->get()->count();

        $todayPostActive = Post::whereDate('created_at', Carbon::now()->addDay(0))->get()->count();

        $viewShareVars = ['activePost','inActivePost','yesterdayPostActive','todayPostActive'];

        return view('dashboard.index',compact($viewShareVars));
    }

As You see all the variables as declared as array of $viewShareVars and Accessed in View

But My Function Becomes very Larger so i have decided to make the line as very simple

public function index()
    {
        $activePost = Post::where('status','=','active')->get()->count();

        $inActivePost = Post::where('status','=','inactive')->get()->count();

        $yesterdayPostActive = Post::whereDate('created_at', Carbon::now()->addDay(-1))->get()->count();

        $todayPostActive = Post::whereDate('created_at', Carbon::now()->addDay(0))->get()->count();

        $viewShareVars = array_keys(get_defined_vars());

        return view('dashboard.index',compact($viewShareVars));
    }

the native php function get_defined_vars() get all the defined variables from the function

and array_keys will grab the variable names

so in your view you can access all the declared variable inside the function

as {{$todayPostActive}}

Outfielder answered 19/3, 2019 at 7:10 Comment(1)
You save my day, thanks! I think this a great solution.Mask
D
4

Came across a similar problem, but if you do not necessarily want to return a view with view file, you can do this:

return $view->with(compact('myVar1', 'myVar2', ..... , 'myLastVar'));
Dittany answered 27/1, 2016 at 3:37 Comment(0)
S
4

with function and single parameters:

    $ms = Person::where('name', 'Foo Bar');
    $persons = Person::order_by('list_order', 'ASC')->get();
    return $view->with(compact('ms', 'persons'));

with function and array parameter:

    $ms = Person::where('name', 'Foo Bar');
    $persons = Person::order_by('list_order', 'ASC')->get();
    $array = ['ms' => $ms, 'persons' => $persons];
    return $view->with($array);
Serenata answered 20/10, 2020 at 7:16 Comment(0)
K
2

Please try this,

$ms = Person::where('name', 'Foo Bar')->first();
$persons = Person::order_by('list_order', 'ASC')->get();
return View::make('viewname')->with(compact('persons','ms'));
Knobkerrie answered 21/9, 2018 at 18:29 Comment(0)
F
1
    $oblast = Oblast::all();
    $category = Category::where('slug', $catName)->first();
    $availableProjects = $category->availableProjects;
    return view('pages.business-area')->with(array('category'=>$category, 'availableProjects'=>$availableProjects, 'oblast'=>$oblast));
Furlani answered 11/1, 2019 at 13:10 Comment(0)
W
0

For passing multiple array data from controller to view, try it. It is working. In this example, I am passing subject details from a table and subject details contain category id, the details like name if category id is fetched from another table category.

$category = Category::all();
$category = Category::pluck('name', 'id');
$item = Subject::find($id);
return View::make('subject.edit')->with(array('item'=>$item, 'category'=>$category));
Watt answered 27/12, 2017 at 10:6 Comment(0)
E
0

If your using laravel, try this:

return view('app-student.app-student dashboard',compact('education_level_data','student_data',.......n));
where by:
1. education_level_data----first-parameter
2. student_data ----second parameter
NB: And you can pass more parameters as much as you can.
Ecumenical answered 10/4, 2022 at 21:27 Comment(0)
W
-4

Its simple :)

<link rel="icon" href="{{ asset('favicon.ico')}}" type="image/x-icon" />
Wilber answered 7/9, 2019 at 8:37 Comment(1)
This one seems a bit out of place in comparison to other answers.Demesne

© 2022 - 2024 — McMap. All rights reserved.