Jason V. Castellano
Jason V. Castellano

Reputation: 316

I cannot access model methods when using DB Facade in laravel

I have this model and I don't want to use eloquent due to some performance and slow query, even though I'm using Eager Loading the performance changes little bit. But unlike DB Facade the query is much faster. My problem is how can I access the method inside my model by using DB Facade?

----------------------
    Table: user
    id | fname | lname
-----------------------

and this is my model

class User extends Model {
    public function complete_name() {
       return $this->fname . " ".$this->lname;
    }
}

but when Im using

$users = DB::table('user')->get();

and loop through it

$result = [];
    foreach ($users as $user) {
     $result[] = $user->complete_name();
    }
return $result;

I cannot access the method "complete_name()". Is there any techniques or style in order for me to access the method inside User class?

Upvotes: 0

Views: 878

Answers (3)

Rahman Rezaee
Rahman Rezaee

Reputation: 2165

For using methods in model you must use eloquent instead query builder Like first answer

otherwise

public function index(){

    $users = DB::table('user')->get();

    $result = [];
    foreach ($users as $user) {
       $result[] = $this->complete_name($user);
    }
    return $result;

}

public function complete_name($user) {
   return $user->fname . " ".$user->user;
}

Upvotes: 0

Ashraful Islam
Ashraful Islam

Reputation: 11

your model User.php

class User extends Model {

   public function complete_name() {
      return $this->fname . " ".$this->lname;
   }

}

You can also use like this

use App\User;

$users = User::all();

Then You can access your complete_name() method.

$result = [];
foreach ($users as $user) {
  $result[] = $user->complete_name();
}
return $result;

Upvotes: 1

Zia Yamin
Zia Yamin

Reputation: 1004

there is no need to call the complete_name method on there, because the Query builder not return model. you can write your code like below:

$users = DB::table('user')->get();

your loop could be like:

$result = [];
foreach ($users as $user) {
    $result[] =$user->fname.' '. $user->lname;
}
return $result;

Upvotes: 0

Related Questions