How to Call Model Function in Controller Laravel

Laravel Model functions usually hold information related to database tables, column types, or to get Database information. During application development, we can fetch records from database using Model functions and when we call Model function in Controller. We can directly pass that fetched data to a View blade file. The explanation below is a simple example of how the MVC (Model View Controller) structure in Laravel works together.

Create New Function

Firstly, we will create a new function and define it in the Model Class. We will use it to count the number of customers in the ‘custs’ database table. The CustModel, will be as shown below.

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
 
class Cust extends Model
{
  public function totalCusts() {
    $custs= DB::table('custs')->get(); 
    return $custs->count(); 
  }
}

Call to Model Function in Controller

Now we will move to the Controller Class. Here we will make a call to the function defined in the Model Class. The code below calls the Model function.

<?php
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use App\Models\Cust;
 
class CustController extends Model
{
  public function index() {
    $cust = new Cust; 
    $total_custs =  $cust->totalCusts(); 
    return view ('HomePage')->with(
            'total_customers' => $total_custs);
  }
}

The code above assigns the Cust model to the $cust variable and makes a call to the totalCusts() method from the Cust Model. This counts the number of customers in the cust table, as defined in the Model function. The result then returns in the index method which you can display in the HomePage View blade.

This makes it easier to access database information without writing complex queries in the Controller Class. The Model can be connected to Controller and database information can be handled in the Model itself.