How to get data from a model on all pages in Laravel – Simple Way

Do you know How to get data from a model on all pages in Laravel ? In this blog post, i will explain that.

normally in Laravel, we have to use controllers and models to get data from a database to a view. today I will show you how to call a model two all pages of a Laravel application.

For that, we have to modify the AppServiceProvider.php file. we have to add some codes inside the boot() function.

Step 1: Go to app/Providers/AppServiceProvider.php

app/Providers/AppServiceProvider.php 

Step 2: Add View Share function

use App\Models\setting;   //call your model
 
class AppServiceProvider extends ServiceProvider 
{
    public function boot() 
    {
        $setings = setting::find(1);                   
        View::share(['settings' =>$setings]);   
    }
}

Step 3: Call the data in Blade template

{{ $settings->websitename }}

Thats all . this is how its works ..  i will give you another example how you can call a single variable to all views

 

How to call a variable in all views in Laravel

class AppServiceProvider extends ServiceProvider 
{
    public function boot() 
    {
        view()->share('sitename', 'My Awesome Website');
    }
}

Same like in blade template you can call this anywhere

{{$sitename}}

Simple as that. Hope this helps

Check out other awesome Laravel tutorials 

 

 

 

 

 

 

 

 

Ajith Jojo Joseph

Hire Me for Freelancing $30/Hour ,
Contact via email : [email protected]

Share with your friends:

Comments are closed.

How To Generate A PDF from HTML in Laravel 11

Hello , I was trying to generate a PDF payment receipt for my SAAS application and when i search for […]

June 22, 2024

How to create Laravel Flash Messages

Laravel flash messages are a convenient way to display one-time notifications to the user after a form submission or other […]

December 22, 2022

How to make Custom Artisan Command in Laravel

Custom Artisan commands are a useful feature of Laravel that allow you to define your own command-line commands for tasks […]

December 22, 2022

Tips for Laravel migrations

Laravel migrations are a powerful tool for managing and modifying your database schema in a structured and organized way. Here […]

December 22, 2022

Digital Marketing Toolkit

Get Free Access to Digital Marketing Toolkit. You can use all our tools without any limits

Get Free Access Now