0

I have a middleware file called LanguageMiddleware.php:

...
class LanguageMiddleware {

    //ISO language codes:
    public $languages = ['en','es','fr','de','pt','pl','zh','ja'];
    ...

LanguageMiddleware.php is in laravelProj/app/Http/Middleware/

Here's my problem: I have a blade template file called master.blade.php where I'm attempting to output a list of languages

@foreach (App\Http\Middleware\LanguageMiddleware\languages as $lang)
    <a class=\"setLang\" href=\"lang/en\">{{ Locale::getDisplayLanguage($lang, $lang) }}</a><br>
@endforeach

I need to access the $languages variable in LanguageMiddleware.php

master.blade.php is in laravelProj/resources/views/layouts/

How to access variables in another class?

2 Answers 2

3

That's simple php stuff. Set the attribute as static and access it with ::.

class LanguageMiddleware {
    public static $languages = ['en','es','fr','de','pt','pl','zh','ja'];
}

@foreach (App\Http\Middleware\LanguageMiddleware::$languages as $lang)
    ...
@endforeach

You should not have that in a middleware though. You'd better add a configuration (i.e in /config/app.php) with that array, and access it with Config::get.

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

2 Comments

Seconded: if languages need to be accessed outside of the middleware, then move them out of the middleware to somewhere that is accessible by both.
I know it might seem simple, but I am only finding this stuff out and am trying to do it the right way. Thank you for your tip about Config::get... That is certainly what I should be doing!
1

The best way is to have a class with a function that can be access outside of its scope. I normally do something like this one here:

In app directory you can create a new directory (e.g libs),

put LanguageMiddleware.php in there,

class LanguageMiddleware{
 static function languages($lang){
   //Do your languages code here
}
}

In app/start/global.php add app_path().'/libs' to you addDirectories, Then in composer.json add "app/libs" to autoLoad array.

In your blade template you can do:

@foreach(LanguageMiddleware::languages($lang))
  <a class=\"setLang\" href=\"lang/en\">{{ Locale::getDisplayLanguage($lang, $lang) }}</a><br>
@endforeach

This way the class and its function is now available wherever you want to call it in your project.

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.