Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Famine's avatar

Passing variable from included PHP file into a view

Hi guys,

Laravel noob here. I have an external PHP file for IP geolocation that I've included in my composer.json:

"files": ["resources/inc/geo.php"]

I then ran the commands "composer update" and "composer install".

Within geo.php, I set a variable $flag. How can I pass this variable to a view? Or better yet, make it available to any view in my application?

Thanks!

0 likes
7 replies
davorminchorov's avatar

When you include files in composer.json, do composer dump-autoload (or any of the other similar commands) instead of composer update / install because it's quicker. Also, if you are using Laravel 5, all classes in the project should be automatically loaded without including them separately.

I am assuming Geo.php is a class, so you can inject an object in the controller's constructor or method, where you want to pass the $flag variable.

Example (single view or few specific views):


protected $flag;

public function __construct(Geo $flag)
{
    $this->flag = $flag;
}

public function name()
{
    $flag = $this->flag;
    return view('name_of_view', compact('flag')); // or use any of the other ways to pass a variable to a view;
}

So in the view, you should be able to access the properties and methods of the class Geo via the $flag variable.

Views Documentation

Famine's avatar

Sorry I should clarify. My geo.php simply contains a variable, i.e:

$flag = "US";

If I try this: View::share(compact('flag'));

I get "Undefined variable: flag"

Kemito's avatar

@Famine

$flag = 'US';
View::share(compact('flag'));

this must be in the same file.

Famine's avatar

If they must be in the same file... how am I supposed to use the variable $flag with

View::share(compact('flag'));

The $flag variable is in a file that I've included in my composer.json autoload section.

Famine's avatar

Although I still don't know the answer to this, I ended up migrating the simple logic in my geo.php file into a Laravel Service Provider.

Within my new GeoServiceProvider, I made $flag available to all views using

view()->share('flag',$flag);

This now works in all my views using blade syntax

{{ $flag }}

Please or to participate in this conversation.