0

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!

3
  • I guess I miss that part, any specific comment instead of a general link? Commented Jan 19, 2017 at 4:42
  • You did not even understand the question. you should receive a penalty for downvoting with no reason and giving pointless answer... Commented Jan 19, 2017 at 4:48
  • Guys, please look at the question. It's a very valid question. Don't downvote like that Commented Jan 19, 2017 at 4:51

3 Answers 3

2

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!

Sign up to request clarification or add additional context in comments.

2 Comments

Awesome that was the answer I was looking for. There should be penalty for downvoters with no reason.
Cheers @Eduardo, they didn't understand the question. I'll upvote you to get the count back to zero
0

Try this to pass data in view

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

Comments

0

Try this, it works.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.