Laravel 5.3 Model.php 行 2709 中的 ErrorException

Laravel 5.3 ErrorException in Model.php line 2709

我正在使用 Laravel 5.3,我想使用以下方式发送验证邮件

php artisen make:auth
php artisen make:mail ConfirmationEmail

ConfirmationEmail.php

<?php

namespace App\Mail;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class ConfirmationEmail extends Mailable
{
use Queueable, SerializesModels;

/**
 * Create a new message instance.
 *
 * @return void
 */
public $user;
public function __construct(User $user)
{
    $this->user = $user;
}

/**
 * Build the message.
 *
 * @return $this
 */
public function build()
{
    return $this->view('emails.confirmation');
}
}

emails/confirmation.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Sign Up Confirmation</title>
</head>
<body>
  <h1>Thanks for signing up!</h1>

  <p>
    We just need you to <a href='{{ url("register/confirm/{$user->token}") }}'>confirm your email address</a> real quick!
</p>
</body>
</html>

UserController.php

public function register(Request $request)
{
    $validator = Validator::make($request->all(), [
        'email'         => 'required|email|unique:users',
        'name'          => 'required|string',
        'password'      => 'required|string|min:6',
        'country'       => 'required'
    ]);
    if ($validator->fails()) {
        return response()->json(['error'=>$validator->errors()], 401);
    }
    $input = $request->all();
    $input['password'] = bcrypt($input['password']);
    $input['user_pin'] = $this->generatePIN();
    $user = User::create($input);
    Mail::to($user->email)->send(new ConfirmationEmail($user));
    $success['token'] =  $user->createToken('MyApp')->accessToken;
    $success['user']  =  $user ;
    $now      = Carbon::now();
    UserLocation::create(['user_pin' => $input['user_pin'] , 'lat'=> 0.0 , 'lng' => 0.0 , 'located_at' => $now]);
    return response()->json(['success'=>$success], $this->successStatus);
}

Models/User.php

<?php

vnamespace App\Models;
use App\User as BaseUser;

class User extends BaseUser
 {

  /**
  * The attributes that should be hidden for arrays.
  *
  * @var array
  */
  protected $hidden = [
    'password', 'remember_token',
  ];


  public function groups(){
    return $this->belongsToMany(Group::class, 'group_member', 'member_id', 'group_id');
  }

public function sentRequests(){
    return $this->hasMany(Request::class, 'from_user_pin', 'user_pin');
  }

public function receivedRequests(){
    return $this->hasMany(Request::class, 'to_user_pin', 'user_pin');
  }

public function locations(){
    return $this->hasMany(UserLocation::class, 'user_pin', 'user_pin');
  }
}

App\User.php

<?php

namespace App;

use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;


class User extends Authenticatable
{
 use HasApiTokens, Notifiable;


protected $guarded = ['id'];

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
/*protected $fillable = [
    'name', 'email', 'password',
];*/

/**
 * The attributes excluded from the model's JSON form.
 *
 * @var array
 */
 protected $hidden = [
    'password', 'remember_token',
 ];

}

我现在遇到这个错误

ErrorException in Model.php line 2709: Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation (View: /var/www/html/group_map_v1/resources/views/emails/confirmation.blade.php)

您收到此错误,您正在尝试将模型方法用作关系,但此方法不是 return 关系。关系应如下所示:

public function relationship()
{
    return $this->hasMany(Model::class);
}

更新

HasApiTokens trait 有一个名为 token() 的方法,它是一个简单的访问器:

public function token()
{
    return $this->accessToken;
}

当您执行 $user->token 时,Laravel 会看到此方法并尝试将其用作关系。

因此,您要做的是将 users table 中的 token 属性 重命名为其他名称。

感谢@lagbox 指出正确的方向。

token是模型上的方法。当您尝试访问模型上的动态 属性 时,它会查找一个属性,然后使用该名称查找关系方法(或已加载的关系)。

您没有名为 token 的属性。当您尝试通过动态 属性 访问它时,它会查找名为 token 的方法(这就是它如何通过 属性 访问关系)。当它执行此操作时,它会调用该方法,而该方法不会 return 关系类型对象。所以 Eloquent 在那一点中断,因为 属性 用于属性和关系,它不能用它做任何事情。

asklagbox - blog - eloquent misunderstandings - dynamic properties and relationships