No idea why I'm getting this error...
Call to a member function getRememberToken() on null (View: /home/vagrant/temptools/resources/views/layouts/main.blade.php) (View: /home/vagrant/temptools/resources/views/layouts/main.blade.php)
I have an Auth::check() on that blade page
I'm using https://github.com/invisnik/laravel-steam-auth
Routes:
Route::get('login', 'AuthController#redirectToSteam')->name('login');
Route::get('login/handle', 'AuthController#handle')->name('login.handle');
Route::post('logout', 'Auth\LoginController#logout')->name('logout');
AuthController:
namespace App\Http\Controllers;
use Invisnik\LaravelSteamAuth\SteamAuth;
use App\User;
use Auth;
class AuthController extends Controller
{
/**
* The SteamAuth instance.
*
* #var SteamAuth
*/
protected $steam;
/**
* The redirect URL.
*
* #var string
*/
protected $redirectURL = '/';
/**
* AuthController constructor.
*
* #param SteamAuth $steam
*/
public function __construct(SteamAuth $steam)
{
$this->steam = $steam;
}
/**
* Redirect the user to the authentication page
*
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function redirectToSteam()
{
return $this->steam->redirect();
}
/**
* Get user info and log in
*
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function handle()
{
if ($this->steam->validate()) {
$info = $this->steam->getUserInfo();
if (!is_null($info)) {
$user = $this->findOrNewUser($info);
Auth::login($user, true);
return redirect($this->redirectURL); // redirect to site
}
}
return $this->redirectToSteam();
}
/**
* Getting user by info or created if not exists
*
* #param $info
* #return User
*/
protected function findOrNewUser($info)
{
$user = User::where('id', $info->steamID64)->first();
if (!is_null($user)) {
return $user;
}
return User::create([
'name' => $info->personaname,
'avatar' => $info->avatarfull,
'id' => $info->steamID64
]);
}
}
app/User:
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'id', 'name', 'avatar',
];
protected $hidden = [
'remember_token',
];
}
create_users_table migration:
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigInteger('id')->unsigned();
$table->string('name');
$table->string('avatar');
$table->rememberToken();
$table->timestamps();
$table->primary('id');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
Have deleted the password recovery migration.
I also get the error if I hit the logout path:
Call to a member function getRememberToken() on null
========
Looking into errors, the error seems to be in laravel/framework/sec/Illuminate/Auth/EloquentUserProvider.php line 67
public function retrieveByToken($identifier, $token)
{
$model = $this->createModel();
$model = $model->where($model->getAuthIdentifierName(), $identifier)->first();
$rememberToken = $model->getRememberToken();
return $model && $rememberToken && hash_equals($rememberToken, $token) ? $model : null;
}
Still no idea how to fix it though
Looks like this package uses Laravel Auth... How do you set unique ID for your users? Generally you should auto increment them... Don't forget that Laravel's auth is reliant on many conventions... Look at AuthenticatesUsers trait for a peek... but one of the fields required is email...
trait AuthenticatesUsers
{
/**
* Get the login username to be used by the controller.
*
* #return string
*/
public function username()
{
return 'email';
}
}
Take a look around the Auth structure, look at the default 'web' guard (look at auth.php in the config directory as a starting point... ).
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique(); //Unique ID for login in laravel? The AuthenticatesUser trait uses email as username...
$table->string('password');
$table->string('avatar');
$table->rememberToken();
$table->timestamps();
});
}
Hope this helps...
Go into this function parent:
public function retrieveByToken($identifier, $token){
$model = $this->createModel();
$model = $model->where($model->getAuthIdentifierName(), $identifier)->first();
$rememberToken = $model->getRememberToken();
return $model && $rememberToken && hash_equals($rememberToken, $token) ? $model : null;
}
dump the model and $identifier,
create a model row with that identifier and it will fixed!
Related
Employee Controller
<?php
namespace App\Http\Controllers;
use App\Talent\Employee\Requests\EmployeeCreateRequest;
use App\Talent\Employee\EmployeeManager;
use Illuminate\Http\Response;
use App\Talent\User\UserManager;
use App\Talent\Documents\DocumentManager;
use Illuminate\Support\Facades\Hash;
class EmployeeController extends Controller
{
public function __construct(private EmployeeManager $employeeManager,private UserManager $userManager,private DocumentManager $documentManager)
{
}
public function store(EmployeeCreateRequest $request){
$validated = $request->validated();
$userArray=[
'name'=>$validated['first_name']." ".$validated['last_name'],
'email'=>$validated['email'],
'password'=>Hash::make("Introcept#123"),
'role'=>'user'
];
$userCreate=$this->userManager->store($userArray);
return $this->employeeStore($validated,$userCreate,$request);
}
public function employeeStore($validated,$userCreate,$request){
if($request->hasFile($validated['avatar']))
{
$validated['avatar']=$validated['avatar']->store('employeeimages','public');
}
else
{
$validated['avatar']='null';
}
$userId=$userCreate->id;
$userIdArray=[
'user_id'=>$userId,
'status'=>'Active',
];
$employeeArray=array_merge($validated,$userIdArray);
$employeeCreate=$this->employeeManager->store($employeeArray);
$employeeId=$employeeCreate->id;
foreach($validated['documents'] as $document){
$name=$document->getClientOriginalName();
$type=$document->getClientMimeType();
$path=$document->store('employeedocuments','public');
$documentArray=[
'employee_id'=>$employeeId,
'original_name'=>$name,
'type'=>$type,
'path'=>$path,
];
$documentCreate=$this->documentManager->store($documentArray);
}
return response([
'userId'=>$userId,
'employeeId'=>$employeeId,
'message'=>'Personal detail added successfully',
],Response::HTTP_OK);
}
}
Employee.php
<?php
namespace App\Talent\Employee\Model;
use App\Talent\Documents\Model\Document;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Employee extends Model
{
use HasFactory;
protected $fillable = [
'first_name',
'last_name',
'email',
'contact_number',
'date_of_birth',
'current_address',
'pan_number',
'bank_account_number',
'avatar',
'status',
'user_id',
];
**EmployeeRequest.php**
<?php
namespace App\Talent\Employee\Requests;
use Illuminate\Foundation\Http\FormRequest;
class EmployeeCreateRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array<string, mixed>
*/
public function rules()
{
return [
'first_name'=>'required|string',
'last_name'=>'required|string',
'email'=>'required|email|unique:employees,email',
'contact_number'=>'required|string',
'date_of_birth'=>'required|date',
'current_address'=>'required|string',
'pan_number'=>'string|nullable',
'bank_account_number'=>'string|nullable',
'avatar' => 'nullable|image|mimes:jpg,jpeg,png',
'documents'=>'required',
'documents.*'=>'max:5000|mimes:pdf,png,jpg,jpeg',
];
}
public function messages()
{
return [
'documents.max' => "Error uploading file:File too big.Max file size:5MB",
];
}
}
EmployeeMigration
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('employees', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained('users')->restrictOnDelete();
$table->string('status');
$table->string('first_name');
$table->string('last_name');
$table->string('email')->unique();
$table->string('contact_number');
$table->date('date_of_birth');
$table->string('current_address');
$table->string('pan_number')->nullable();
$table->string('bank_account_number')->nullable();
$table->string('avatar')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('employees');
}
};
I am trying to create an API that stores employee personal details into the database. Here, image field is optional so I made avatar field nullable in both migration and validation request as well. But when I try save details into the database without uploading image it shows undefined avatar. I don't know what happening here any help or suggestions will be really appreciated. Thank you.
You are using the string value of null instead of the keyword null.
I'm having trouble updating the github_oauth_token and github_oauth_refresh_token fields in my User model that have the encrypted cast. All other fields update fine and the casting is working as expected however the fields will not save to the database.
User model
namespace App\Models;
use App\Mail\EmailVerification;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Validator;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Mail;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'first_name',
'last_name',
'email',
'email_verification_token',
'password',
'github_oauth_token',
'github_oauth_refresh_token',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
'github_oauth_token' => 'encrypted',
'github_oauth_refresh_token' => 'encrypted',
];
/**
* Set the user's github oauth token.
*
* #param string $value
* #return void
*/
public function setGithubOauthTokenAttribute($value)
{
$this->github_oauth_token = Crypt::encryptString($value);
}
/**
* Set the user's github oauth refresh token.
*
* #param string $value
* #return void
*/
public function setGithubOauthRefreshTokenAttribute($value)
{
$this->github_oauth_refresh_token = Crypt::encryptString($value);
}
}
User migration
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('first_name', 45);
$table->string('last_name', 45);
$table->string('email')->unique();
$table->string('email_verification_token', 30)->nullable();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->string('github_oauth_token')->nullable();
$table->string('github_oauth_refresh_token')->nullable();
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
Controller method
public function handleGitHubCallback()
{
$gitHubUser = Socialite::driver('github')->user();
$user = Auth::user();
$user->github_oauth_token = $gitHubUser->token; // does not update
$user->github_oauth_refresh_token = $gitHubUser->refreshToken; // does not update
$user->first_name = 'Johnathan'; // updates fine
$user->save();
return redirect()->route('space.list.get')->with('success', Lang::get('messages.success_github_linked'));
}
The issue is in User Model.You are casting both fields in $cast property
protected $casts = [
'email_verified_at' => 'datetime',
'github_oauth_token' => 'encrypted',
'github_oauth_refresh_token' => 'encrypted',
];
So no need to add Mutators so remove both below Mutators.
public function setGithubOauthTokenAttribute($value)
{
$this->github_oauth_token = Crypt::encryptString($value);
}
public function setGithubOauthRefreshTokenAttribute($value)
{
$this->github_oauth_refresh_token = Crypt::encryptString($value);
}
Also if you want to use mutators then you have an error it should b like below
public function setGithubOauthTokenAttribute($value)
{
$this->attributes['github_oauth_token ']= Crypt::encryptString($value);
}
public function setGithubOauthRefreshTokenAttribute($value)
{
$this->attributes['github_oauth_refresh_token ']= Crypt::encryptString($value);
}
I am using solcialite to login Laravel via Gihub, but there is problem to login. I get a error: Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_RECOVERABLE_ERROR)
Type error: Argument 1 passed to Illuminate\Auth\SessionGuard::login() must implement interface Illuminate\Contracts\Auth\Authenticatable, null given, called in /var/www/html/testio/vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php on line 292
My LoginController:
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Socialite;
use App\User;
use Auth;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = '/home';
public function __construct()
{
$this->middleware('guest')->except('logout');
}
/**
* Redirect the user to the GitHub authentication page.
*
* #return \Illuminate\Http\Response
*/
public function redirectToProvider()
{
return Socialite::driver('github')->redirect();
}
/**
* Obtain the user information from GitHub.
*
* #return \Illuminate\Http\Response
*/
public function handleProviderCallback()
{
$github_user = Socialite::driver('github')->user();
$user = $this->userFindorCreate($github_user);
Auth::login($user, true);
return redirect('/home');
// $user->token;
}
public function userFindorCreate($github_user){
$user = User::where('provider_id', $github_user->id)->first();
if(!$user){
$user = new User;
$user->name = $github_user->getName();
$user->email = $github_user->getEmail();
$user->provider_id = $github_user->getid();
$user->save();
}
}
}
My User.php model:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Foundation\Auth\User as AuthUser;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'email',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
create_users_table :
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->nullable();
$table->string('email')->unique();
$table->string('password')->nullable();
$table->string('provider_id');
$table->rememberToken();
$table->timestamps();
});
}
Damn it what I am doing wrong?
I missed return $users; on last function:
public function userFindorCreate($github_user){
$user = User::where('provider_id', $github_user->id)->first();
if(!$user){
$user = new User;
$user->name = 'jojo';
$user->email = $github_user->getEmail();
$user->provider_id = $github_user->getid();
$user->save();
}
return $user;
}
i have problem with creating cateogories.
before i change the category relationship to many to many i didnt have problem.
whene i post new category and after that its redirect to category list page, i got this error:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'myblog.category_post' doesn't exist (SQL: select posts.*, category_post.category_id as pivot_category_id, category_post.post_id as pivot_post_id from posts inner join category_post on posts.id = category_post.post_id where category_post.category_id = 1) (View: C:\Users\M0RT3Z4\Desktop\MyBlog\resources\views\admin\category\index.blade.php)
but the category insert in database. if a record insert in to category table, the category list will not show and i will get error.
Post Model:
namespace App\Models;
use Cviebrock\EloquentSluggable\Sluggable;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use Sluggable;
protected $fillable = [
'title', 'body', 'views', 'category_id', 'user_id'
];
public function comment()
{
$this->hasMany(Comment::class);
}
public function category()
{
return $this->belongsToMany(Category::class);
}
public function tags()
{
return $this->belongsToMany(Tag::class);
}
/**
* Return the sluggable configuration array for this model.
*
* #return array
*/
public function sluggable(): array
{
return [
'slug' => [
'source' => 'title'
]
];
}
public function hastags($id)
{
return in_array($id, $this->tags()->pluck('id')->toArray());
}
public function hascategories($id)
{
return in_array($id,$this->category()->pluck('id')->toArray());
}
}
Category Model:
<?php
namespace App\Models;
use Cviebrock\EloquentSluggable\Sluggable;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
use Sluggable;
protected $fillable = [
'name','slug'
];
public function post()
{
return $this->belongsToMany(Post::class);
}
/**
* Return the sluggable configuration array for this model.
*
* #return array
*/
public function sluggable(): array
{
return [
'slug' => [
'source' => 'name'
]
];
}
}
CategoryController:
<?php
namespace App\Http\Controllers\Admin;
use App\Models\Category;
use App\Models\Post;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Session;
class CategoryController extends Controller
{
public function index()
{
$post = Post::all();
$cats = Category::orderBy('id','DESC')->paginate(10);
return view('admin.category.index',compact(['cats','post']));
}
public function create()
{
return view('admin.category.create');
}
public function show(Category $category)
{
return view('admin.category.show',compact('category'));
}
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|min:3|unique:categories',
]);
$cat = new Category();
$cat->name = $request->name;
$cat->slug = $request->slug;
$cat->save();
Session::flash('success','Category Created Successfully');
return redirect()->route('admin.category.index');
}
public function edit(Category $category)
{
return view('admin.category.edit',compact('category'));
}
public function update(Category $category,Request $request)
{
$this->validate($request, [
'name' => 'required|min:3|unique:categories',
]);
$category->name = $request->name;
$category->save();
Session::flash('update','Category Updated Successfully');
return redirect()->route('admin.category.index');
}
public function destroy(Category $category)
{
$category->delete();
Session::flash('delete','Category Deleted Successfully');
return redirect()->route('admin.category.index');
}
}
categories migration:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCategoriesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('slug');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('categories');
}
}
post_category migration
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostCategory extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('post_category', function (Blueprint $table) {
$table->unsignedInteger('post_id');
$table->unsignedInteger('category_id');
$table->foreign('post_id')->on('posts')->references('id')->onUpdate('cascade')->onDelete('cascade');
$table->foreign('category_id')->on('categories')->references('id')->onUpdate('cascade')->onDelete('cascade');
$table->unique(['post_id', 'category_id']);
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('post_category');
}
}
posts migration
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title')->unique();
$table->string('slug')->unique()->nullable();
$table->text('body');
$table->string('image')->nullable();
$table->unsignedInteger('views')->default(0);
$table->unsignedInteger('category_id')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
you should use best practice for migration naming convention to avoid this issue
rename create_post_category to category_post (alphabetical order)
or you can specify within $this->belongsToMany(Category::class,'category_post') additional arguments for the pivot table and keys
I'm trying to install this https://github.com/invisnik/laravel-steam-auth (with some of my own custom fields)
It works fine and all except for that it doesn't create the users (it creates the table) when I log in and I don't know why.
AuthController.php
namespace App\Http\Controllers;
use Invisnik\LaravelSteamAuth\SteamAuth;
use App\User;
use Auth;
class AuthController extends Controller
{
/**
* #var SteamAuth
*/
private $steam;
public function __construct(SteamAuth $steam)
{
$this->steam = $steam;
}
public function login()
{
if ($this->steam->validate()) {
$info = $this->steam->getUserInfo();
if (!is_null($info)) {
$user = User::where('steamid', $info->steamID64)->first();
if (is_null($user)) {
$user = User::create([
'username' => $info->personaname,
'avatar' => $info->avatarfull,
'steamid' => $info->steamID64
]);
}
Auth::login($user, true);
return redirect('/'); // redirect to site
}
}
return $this->steam->redirect(); // redirect to Steam login page
}
}
create_users_table.php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('nickname');
$table->string('avatar');
$table->string('steamid')->unique();
$table->string('name');
$table->string('rank');
$table->string('community_id');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
web.php
Route::get('login', 'AuthController#login')->name('login');
Route::post('logout', 'Auth\LoginController#logout')->name('logout');
steam-auth.php
return [
/*
* Redirect URL after login
*/
'redirect_url' => '/',
/*
* API Key (http://steamcommunity.com/dev/apikey)
*/
'api_key' => 'xxx',
/*
* Is using https ?
*/
'https' => false
];
User.php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['nickname', 'avatar', 'steamid', 'name', 'rank', 'community_id', 'email', 'password'];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
Any ideas?
UPDATE:
$info seems to return null and I have no clue why.