user3478148
user3478148

Reputation: 443

The best way to return a variable in my app.blade.php Laravel

I'm using Laravel to build a CMS and I have a View Site button that's available in my main layout file (if that's how you call it) app.blade.php. This file is where I yield my content and load all my css and js files.

I want the link of the View Site button to be dynamic, based on a base url set in my settings table. I can retrieve the variable like this:

$settings = DB::table('settings')->get();

return $settings->base_url;

But my question is: how do i retrieve this in my view the right way?

I'm having trouble doing this because usually I link a method to a specific page with the routes.php file, but since the app.blade.php is available everywhere I'm unable to do this (I guess).

Upvotes: 2

Views: 3766

Answers (2)

Andy Noelker
Andy Noelker

Reputation: 11269

You need a view composer. This is a function that can add data to a view every time it is being rendered. It makes the most sense to put your view composer inside of a service provider.

Make a new service provider inside app/Providers, then add your view composer inside of the boot() method.

ViewComposerServiceProvider

namespace App\Providers;

use DB;
use Illuminate\Support\ServiceProvider;

class ViewComposerServiceProvider extends ServiceProvider
{
    public function boot()
    {
        view()->composer('app', function($view) {
            $settings = DB::table('settings')->get();
            $view->with('base_url', $settings->base_url);
        });
    }
}

This would inject a variable called $base_url into app.blade.php every time it was rendered. Of course, instead of adding the view composer as a closure, you could move it out into its own class that just gets included inside the service provider, but this should give you the right idea.

Then just make sure to register your service provider inside config/app.php:

providers => [
    //All other service providers
    App\Providers\ViewComposerServiceProvider::class,
]

This is the preferred "Laravel way" to inject data into views every time they are rendered. This is the way that is the most flexible and scalable because it allows you to modify your views in really any way before rendering them. Laracasts has a really nice free video on the topic.

Upvotes: 4

Jilson Thomas
Jilson Thomas

Reputation: 7303

The best way is to create a helper function and use it in the view template.

In your app folder, create a file: helper.php

function getBaseURL()
{
  return \App\Setting::get()->base_url ;
}

Now in your blade template app.blade.php, you can get it like:

<a href="{{ getBaseURL() }}"> Visit Site</a>

You need to add this helper.php file to the composer autoload.

For that, in your compose.json file,

    "files":[
        "app/helper.php"
    ],

Add this in the autoload part.

Now do a composer dump-autoload

Upvotes: 0

Related Questions