How to use laravel model function inside controller

In this tutorial we will discuss how to call a laravel model function inside a controller method. calling model function in controller. When model function call in laravel controller it gives error.


Create a function inside model

Here we create a function to count users data inside users table. In example show our User model.

App/Models/User.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class UserModel extends Model
{
  public function totalUsers() {
    $users = DB::table('users')->get(); 
    return $users->count(); 
  }
}

UserController use totalUsers() model function

Now we create a UserController for getting total users count data with help of model function.

App/Http/Controllers/UserController.php
<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;

class UserController extends Model
{
  public function index() {
    $user = new User; 
    $total_users =  $user->totalUsers(); 
    return "Total registred users ".$total_users;
  }
}
php laravel developer anmol sharma

Anmol Sharma

I am a software engineer and have experience in web development technologies like php, Laravel, Codeigniter, javascript, jquery, bootstrap and I like to share my deep knowledge by these blogs.

Random tutorial links