Eduardo
Eduardo

Reputation: 1831

Laravel, pass variable to view

I have a doubt. I have been checking laracasts and they show some examples of passing variable(s) from router to a view:

Route::get('about', function() {
    $people = ['Eduardo', 'Paola', 'Chancho'];
    return view('about')->with('people', $people);
});

Route::get('about', function() {
    $people = ['Eduardo', 'Paola', 'Carlos'];
    return view('about')->withPeople($people);
});

The second example, I am not sure how Laravel handle it. I know it works I have test it, but which pattern they use? why is it possible to handle a dynamic variable.

Thanks in advance for your help!

Upvotes: 0

Views: 377

Answers (3)

amit 1984
amit 1984

Reputation: 366

Try this, it works.

Route::get('about', function() {
    $people = ['Eduardo', 'Paola', 'Chancho'];
    return view('about',compact('people'));
});

Upvotes: 0

Sujal Patel
Sujal Patel

Reputation: 2532

Try this to pass data in view

Route::get('about', function() {
$data['people'] = ['Eduardo', 'Paola', 'Chancho'];
return view('about')->withdata($data);
});

Upvotes: 0

Paras
Paras

Reputation: 9455

The second one is handled by Laravel through php's __call magic method. This method redirects all methods that start with 'with' to the with method through this code in the Illuminate\View\View class:

public function __call($method, $parameters)
    {
        if (Str::startsWith($method, 'with')) {
            return $this->with(Str::snake(substr($method, 4)), $parameters[0]);
        }
        throw new BadMethodCallException("Method [$method] does not exist on view.");
    }

As you can see if the method starts with 'with' (Str::startsWith($method, 'with'), Laravel redirects it to the with method return $this->with by taking the first param as the string that follows 'with' Str::snake(substr($method, 4)) and the second param as the first param that was passed $parameters[0]

Hope this helps!

Upvotes: 2

Related Questions