I'm trying to make a simple route to redirect endpoints to a specific URL based on an array/key.
$redirects = [
"/ios" => $GLOBALS['config']['iosAppStoreLink'],
"/android" => $GLOBALS['config']['androidAppStoreLink']
];
/**
* Redirects
*/
foreach($redirects as $endpoint => $url) {
$app->get($endpoint, function($request, $response) {
return $response->withRedirect($url);
});
}
The endpoints get created without issue just once I'm inside of the $app->get
function, it will not allow me to use $url
... I get an Undefined Index
error in my console.
What am I doing wrong here, why am I not able to access the $url
variable?
To allow the function to access the $url
from outside of it's own scope, you could use function() use() {
syntax...
foreach($redirects as $endpoint => $url) {
$app->get($endpoint, function($request, $response) use ($url) {
return $response->withRedirect($url);
});
}