3

I am trying to use the Route::get method to setup the URL structure for my application without repeating Route::get for each item. I am doing this with a foreach loop as follows:

<?php

Route::get('/', function () {
    return view('welcome');
});
$pages = array('about', 'contact', 'faqs');  
foreach ($pages as $page) {
    Route::get($page, function () {
        return view($page);
    });
}

When run I come across the error: "Undefined variable: page". Although I have worked much with procedural PHP, and PHP within CMSs, I am fairly new to Laravel. What am I missing here?

2 Answers 2

9

$page variable is not in the scope of anonymous function [A] where you defined what given route should respond with. Code below has use ($page) added so that variable can be accessed.

<?php

Route::get('/', function () {
    return view('welcome');
});
$pages = array('about', 'contact', 'faqs');  
foreach ($pages as $page) {
    Route::get($page, function () use ($page) { // [A] 
        return view($page);
    }); 
}

Here you can have some follow-up read about nuances of this behaviour.

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

Comments

3

you can do by where method

$pages = array('about', 'contact', 'faqs');  
Route::get('/{page}',function($page) {
    return   view($page);
})->where('page',implode('|',$pages));

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.