Harness the Power of Models in Laravel's Blade Files

Use Model inside Blade File | Write Controller code inside Blade file - Laravel


How to Use Model in Blade File | Laravel



Sometime during development you need to access your model file inside your blade file in order to access the database . In this article we will see how you use model file inside your blade file or you can say we will learn how to write controller code inside our blade file in Laravel .

As Laravel is a PHP framework and provides blade templating system , you can simply use php tag " <php  ?> " tag to write your code as shown below .

Accessing Model using PHP tag :


<?php

      use App\Detail;
      use App\product;

      $detail=Detail::find(3);

      $product=Product::select('*')
               ->where('id','=','1')
               ->get();

?>

Route :


Route::get('/data',function(){
 return view('demo');
});

Example :


@include('layouts.app')

<div class="row">
   <div class="col-3"></div>
   <div class="col-6 text-center">
   <?php

      use App\Detail;
      use App\product;

      $detail=Detail::find(3);

      $product=Product::select('*')
               ->where('id','=','1')
               ->get();

   ?>
   <div class="card">
  <div class="card-body">

    <p>{{ $detail->name }}</p>
    <p>{{ $detail->email }}</p>
    <p>{{ $detail->phone }}</p>

    @foreach($product as $item)
    <p>{{ $item->name }}</p>
    @endforeach
    
  </div>
</div>
</div>
<div class="col-3"></div>
</div>

Output :

How to Use Model in Blade File | Laravel


Previous Post Next Post

Contact Form