没有登录错误的Laravel 5.7身份验证:此集合实例上不存在Property [id]

没有登录错误的Laravel 5.7身份验证:此集合实例上不存在Property [id]

问题描述:

I'm trying to force an authentication without login with Laravel 5.7 like that:

public function login()
{

    $cpf = Request::only('cpf');
    $user = new User;
    $user = $user->where('cpf', $cpf)->get();
    Auth::loginUsingId($user->id);
    return redirect('/perfil');

}

And I get this error: Property [id] does not exist on this collection instance.

When I debug the model User, all the attributes are there. But when I try to get the attributes, I get this error. What I'm doing wrong?

If there's any other way to authenticate without password, It would be helpful!

If cpf is a unique column, then the following will return the object you're looking for:

$user = User::where('cpf', $cpf)->first();

If you do ->get() as in your code, you'll get a Collection with exactly one object in it, and will need to do $user->first()->id.

https://laravel.com/api/5.6/Illuminate/Database/Eloquent/Builder.html#method_get

You aren't using $user for anything else in the method, so you don't really need that object. You can use the value() method instead to get the id directly from the query.

public function login()
{

    $cpf = Request::only('cpf');

    // value() fetches the value of the specified column from the first row of query results
    $id = User::where('cpf', $cpf)->value('id');

    Auth::loginUsingId($id);
    return redirect('/perfil');

}

I'm not really sure about the authentication part, though.

public function login()
{

    $cpf = Request::only('cpf');
    $user = User::where('cpf', $cpf)->first();
    auth()->loginUsingId($user->id);

    return redirect('/perfil');

}