How to show models data into blade file in laravel

How to show models data into blade file in laravel

Do you have any idea How to get records from a model on all view pages in Laravel? In this tutorial, I will show you a simple way to show data in blade files.

Typically in Laravel, we need to use controller and models to get record from a table of database to show data onto view files. today I will tell you the best way to call a model two all pages of a Laravel application.

For this functionality we need to perform some steps:

  • Step: 01 Open AppServiceProvider.php

  • Step: 02 Using View::share fucntion

  • Step: 03 Showing data in blade file

Step 1:

Open AppServiceProvider.php which is available in App/Providers/AppServicesProvider.php

Step 2:

We need to add some lines of code in AppServiceProvider file Boot() function to get data from table of customers to share on blade files. The code is given bellow:

 use App\Models\Customer; //here we are calling model which we want to use
class AppServiceProvider extends ServiceProvider 
{
public function boot() 
{
$customers = Customer::all();//here we can get multiple data or one record also random data 
View::share(['cu' =>$customers]); //here we are sharing data to blade files
}
}

Step 3:

If we want show multiple records so we need to use Foreach loop like:

@foreach($cu as $customer_show)
   <tr>
        <td>{{$customer_show→name}}</td>
        <td>{{$customer_show→email}}</td>
       <td>{{$customer_show→phone}}</td>
   </tr>
@endforeach

If we have a single we will show simply:

{{$cu→name}}

{{$cu→email}}

{{$cu→phone}}

Thank You For reading Tutorial

Login and Registration system in php

Laravel 9 Crud System

Comments (0)

No comments yet!