在 null 上调用成员函数 phone()

Call to a member function phone() on null

我正在尝试使用一对一关系存储 phone 记录。

public function store(Request $request) {

    $user= auth()->user(); 

    $phone= new Phone();

    $phone->cellno= request('cellno');

    $user->phone()->save($phone); 
    return redirect('/phones');
}

documentation 中指出了检索经过身份验证的用户的推荐方法。

行:

$user = auth()->user(); 

应该是:

$user = Auth::user();

并且不要忘记使用 class 授权:

use Illuminate\Support\Facades\Auth;

解释:

auth()user() 方法在您当前的上下文中不可用,因此如果其中 none 个是 $user 将是 null成立。

编辑:

如果 none 用户通过身份验证,身份验证也将 return 无效,您必须按照下面提供的文档来实施它。然后,你可以secure your Routes

基本上你有两个选择:

a) 在路由规范中添加中间件:

Route::resource('phones' , 'PhoneController')->middleware('auth');

b) 将中间件添加到 class 的构造中(推荐用于控制器)

public function __construct()
{
    $this->middleware('auth');
}

之后,如果没有经过身份验证的用户,访问将被限制。