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

baguus's avatar

Passing custom query results to layout template part

Hi I'm a bit confused on how to do this. I have a template part (budget.blade.php) that I'm including in my template (@include). I need to get variables from a custom query based on user into this template part . (users company budget, orders total,...). I tried with a Service provider

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\View\View;
use App\Order;
use App\Product;
use App\Company;
use Auth;

class BudgetServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        view()->composer('layouts.budget', function () {
            // Can I perform my queries here and if how do I pass them to layouts/budget.blade.php?
        });

    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Partial view

<div class="budget-info-wrapper">
    <div class="budget">
        Forseen budget: {{ $var1}}
    Order total: {{ $var2}}
    Difference: {{ $var3}}      
    </div>
</div>

Is this the correct way and If so, how do I pass the variables to my template part?

0 likes
2 replies
Exiax's avatar
Exiax
Best Answer
Level 3

Hey,

this is the correct way to pass variables to a specific template part.

You can pass variables like so:

view()->composer('layouts.budget', function($view) {
    // run your custom queries if needed
    $var1 = DB::table('some_table')
                     ->select(DB::raw('column1, column2'))
                     ->get();

    return $view->with('var1', $var1);
});

Hope that helps!

1 like
baguus's avatar

Great I think this will work. I get the variable through to my view. I guess I had a typo somewhere - I'm sure I tried this before. Thank you

Please or to participate in this conversation.