2016-09-18 71 views
0

我是laravel的新手,我有一些问题来处理与模型和控制器的关系。Model and conroller relationship laravel 5

我的IndexController,其中被称为:

$usersModel = new \App\Models\Users(); 
if ($usersModel->checkOnExistsByEmail($params['user_email'])){ 
    //...find it 
} 

型号文件:

namespace App\Models; 

use Illuminate\Database\Eloquent\Model; 

class Users extends Model { 
    protected $table = 'users_data'; 

    public function scopeCheckOnExistsByEmail($query,$email){ 

     $count = $query->where('user_email','=',$email)->count(); 
     if ($count == 0){ 
      return false; 
     }else{ 
      return true; 
     } 

    } 

} 

之后,我有一个一个错误:

Object of class Illuminate\Database\Eloquent\Builder could not be converted to string 

有人能解释什么我做错了?非常感谢你。

+1

让控制器处理逻辑而不是模型 –

+1

'scopes'不能转换为布尔型,'scopes'必须返回builder – xAoc

回答

1

合适的型号代码:

namespace App\Models; 

use Illuminate\Database\Eloquent\Model; 

class Users extends Model { 
    protected $table = 'users_data'; 

    public function checkOnExistsByEmail($email){ 
     return (bool)$this->where('email', $email)->first(); 
    } 

} 

你不需要使用范围。

1

首先从控制器返回值进行验证,

return $params['user_email'];  

如果你得到的答案,然后尝试按照下面的代码。

你并不需要在模型函数

您需要使用返回,

if(count($usersModel->checkOnExistsByEmail($params['user_email']) > 0)) { //.... } 

模型只使用,

$query->where('email', $email);   

或使用功能使用count ,然后

if($usersModel->checkOnExistsByEmail($params['user_email']) > 0) { //.... }   

我想,这会帮助你。