Access to undeclared static property: User::$rules in laravel - php

public function update($id)
{
$input = Input::all();
$validation = Validator::make($input, User::$rules);
if ($validation->passes())
{
$user = User::find($id);
$user->update($input);
return Redirect::route('users.show', $id);
}
return Redirect::route('users.edit', $id)
->withInput()
->withErrors($validation)
->with('message', 'There were validation errors.');
}
this is what the code i am having, when I attempt to update a record it shows the following error message. Access to undeclared static property: User::$rules
the user model as follows
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
}

I imagine you have a property in your User model like this:
<?php
class User extends Eloquent {
public $rules = array(
'email' => 'required|email|unique:users',
'password' => 'required|min:8',
);
}
This is a class instance property, but you’re trying to access it statically (the error messages tells you such).
Simply add the static keyword to the property:
<?php
class User extends Eloquent {
public static $rules = array(
'email' => 'required|email|unique:users',
'password' => 'required|min:8',
);
}

Related

Socialite : Argument 1 passed to Illuminate\Auth\SessionGuard::login() must implement interface Illuminate\Contracts\Auth\Authenticatable, null given

I made a socialite login using Google and Facebook, but in the SocialiteController section there is an error like the question above.
this is my SocialiteController
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Laravel\Socialite\Facades\Socialite;
use Illuminate\Support\Facades\Auth;
use Spatie\Permission\Models\Role;
use App\SocialAccount;
use App\User;
class SocialiteController extends Controller
{
public function redirectToProvider($provider)
{
return Socialite::driver($provider)->redirect();
}
public function handleProviderCallback($provider)
{
$user = Socialite::driver($provider)->user();
$authUser = $this->findOrCreateUser($user, $provider);
Auth::login($authUser, true);
return redirect('/personal');
}
public function findOrCreateUser($socialUser, $provider)
{
$socialAccount = SocialAccount::where('provider_id', $socialUser->getId())
->where('provider_name', $provider)
->first();
if($socialAccount) {
return $socialAccount->user;
} else {
$user = User::where('email', $socialUser->getEmail())->first();
if(!$user) {
$user = User::create([
'username' => $socialUser->getName(),
'email' => $socialUser->getEmail()
]);
$user->assignRole('Registered');
}
$user->socialAccounts()->create([
'provider_id' => $socialUser->getId(),
'provider_name' => $provider
]);
return $user;
}
}
}
this is my User model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;
use App\Profile;
use App\Article;
use App\Video;
use App\Images;
use App\News;
class User extends Authenticatable Implements MustVerifyEmail
{
use Notifiable, HasRoles;
protected $table = "users";
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'username', 'email', 'password'
];
/**
* 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',
];
public function profile(){
return $this->hasOne(Profile::class);
}
public function article()
{
return $this->hasMany(Article::class);
}
public function socialAccounts()
{
return $this->hasOne(SocialAccount::class);
}
public function video(){
return $this->hasMany(Video::class);
}
public function news(){
return $this->hasMany(News::class);
}
}
the complete error message like this :
Argument 1 passed to Illuminate\Auth\SessionGuard::login() must implement interface Illuminate\Contracts\Auth\Authenticatable, null given, called in /home/asyj6686/public_html/sublaravel/vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php on line 297
Argument 1 passed to Illuminate\Auth\SessionGuard::login() must implement interface Illuminate\Contracts\Auth\Authenticatable, null given
This error is pretty straight-forward. It means that you have passed a null value to the login.
Auth::login($authUser, true);
I don't see anything wrong with the provided code. Therefore, I'm going to guess that you may have simply forgotten to add the inverse relationship with User in the SocialAccount model. This would cause $socialAccount->user to return null and generate the error you are receiving.
App\SocialAccount.php
class SocialAccount extends Model
{
// ...
public function user()
{
return $this->belongsTo(User::class);
}
}
On a side note, shouldn't a User be able to ->hasMany() SocialAccounts?

Laravel Auth::attempt() not actually login

When I am taking an attempt to login it just redirecting to "admin" page with any value. I did all the possible try found in google. But still not having luck. I am badly in need of help. My code is given below :
Controller: LoginController.php
<?php
class LoginController extends BaseController {
public function doLogin()
{
$rules = ['username'=>'required','password'=>'required'];
$credentials = array(
'username' => Input::get('username'),
'password' => Input::get('password')
);
$validation = Validator::make($credentials, $rules);
if($validation->fails()){
return Redirect::back()
->withInput()
->withErrors($validation);
}
else{
Auth::attempt($credentials);
return Redirect::intended('admin');
}
}
public function doLogOut()
{
Auth::logout();
return Redirect::to('/login');
}
}
Model: User.php
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
}
UserTableSeeder:
<?php
class UserTableSeeder extends Seeder {
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$vader = DB::table('users')->insert([
'username' => 'admin',
'password' => Hash::make('admin'),
'created_at' => new DateTime(),
'updated_at' => new DateTime()
]);
}
}
Routes:
Route::post('login','LoginController#doLogIn');
Let's take a closer look at these lines:
else {
Auth::attempt($credentials);
return Redirect::intended('admin');
}
What you're doing in this snippet is
You try to log the user in.
Then you redirect, regardless of whether it worked or not.
If you want to make sure the user is actually logged in, you should wrap the attempt within an if clause.

Laravel/Ardent - on save(), error: Relationship method must return an object of type Illuminate

I'm having some trouble getting my Laravel relationships to work out. In my application, there is a one-to-many relationship between users and ideas. (A user may have multiple ideas.) I'm using Ardent.
Here's my User model:
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
use LaravelBook\Ardent\Ardent;
class User extends Ardent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
protected $fillable = array('first_name', 'last_name', 'email', 'password');
public $validation_errors;
public $autoPurgeRedundantAttributes = true;
public $autoHashPasswordAttributes = true;
public $autoHydrateEntityFromInput = true;
public static $passwordAttributes = array('password');
public static $rules = array(
'first_name' => 'required|between:1,16',
'last_name' => 'required|between:1,16',
'email' => 'required|email|unique:users',
'password' => 'required|between:6,100'
);
public function ideas()
{
return $this->hasMany('Idea');
}
}
And here's my Idea model:
use LaravelBook\Ardent\Ardent;
class Idea extends Ardent {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'ideas';
protected $fillable = array('title');
public $validation_errors;
public $autoPurgeRedundantAttributes = true;
public $autoHydrateEntityFromInput = true;
public static $rules = array(
'title' => 'required'
);
public function user()
{
return $this->belongsTo('User');
}
}
Finally, here's my controller code:
class IdeasController extends BaseController {
public function postInsert()
{
$idea = new Idea;
$idea->user()->associate(Auth::user());
if($idea->save())
{
return Response::json(array(
'success' => true,
'idea_id' => $idea->id,
'title' => $idea->title),
200
);
}
else
{
return Response::json(array(
'success' => false,
'errors' => json_encode($idea->errors)),
400
);
}
}
}
$idea->save() throws the error:
{
"error": {
"type": "LogicException",
"message": "Relationship method must return an object of type Illuminate\\Database\\Eloquent\\Relations\\Relation",
"file": "\/var\/www\/3os\/vendor\/laravel\/framework\/src\/Illuminate\/Database\/Eloquent\/Model.php",
"line": 2498
}
}
At first, I was trying to set the user_id in the Idea like so:
$idea->user_id = Auth::id();
I then changed it to:
$idea->user()->associate(Auth::user());
But the results were the same.
Any suggestions would be much appreciated.
You cannot use associate in that direction, since it can only be used on a belongsTo relationship. In your case, an idea belongs to a user and not the other way around.
I suspect there is an error when saving, as you create an idea without the required title, and you then try to get the errors by calling $idea->errors, while it should be $idea->errors().
associate will work on belognsTo relationship , in your cause what you have to use is Attaching A Related Model. See more about Attaching A Related Mode in documentation.

Why do I get 'Access to undeclared static property? (Laravel)

I'm trying to validate some data. I found this tutorial at scotch.io. I'm using the following in my UsersController to attempt to validate some data:
public function store(){
$validator = Validator::make(Input::all(), User::$rules);
return Redirect::action("UserController#index");
}
However, I keep getting the error 'Access to undeclared static property: User::$rules'. Am I doing something wrong? I've attempted to use 'php artisan dump-autoload'
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
protected $fillable = array(
'username',
'forename',
'surname',
'email',
'telephone',
'password',
'admin',
'customer',
'verification_link'
);
public static $rules = array(
'name' => 'required', // just a normal required validation
'email' => 'required|email|unique:ducks', // required and must be unique in the ducks table
'password' => 'required',
'password_confirm' => 'required|same:password' // required and has to match the password field
);
}
I had the same problem and I couldn't find a solution for me online, and I traced the problem with PHPStorm, and found out that my Class was defined "TWICE" and so it was reading the first one rather than the one I wanted which is the second one.
The problem you probably have is that your migration files include a migration file for the "User" table, and which defines its class as Class User extends Migration { and the definition of the Class User in your Model will go like Class User extends Eloquent and so the solution is to change one of them to either:
Class CreateUser extends Migration or Class UserModel extends Eloquent
and then use the Model's method according to your change, so you either keep it
User::$rules or UserModel::$rules and that's only if you've changed your Model Class name.

laravel inserting into multiple tables

I have 2 tables
#something - id, name, url
#something_users - id, id_something, email, password
My models
class Something extends Eloquent
{
protected $table = 'something';
protected $fillable = ['name', 'email', 'password'];
public $errors;
public function User()
{
return $this->belongsTo('User', 'id', 'id_something');
}
}
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $table = 'something_users';
protected $hidden = array('password', 'remember_token');
public function Something()
{
return $this->belongsTo('Something');
}
}
Controller
$input = Input::all();
// also some validation
$this->db->fill($input);
$this->db->password = Hash::make(Input::get('password'));
$this->db->push();
$this->db->save();
SQL
insert into `something` (`name`, `email`, `password`) values...
I need to insert name into the first table(something) and email, password into second(something_users)
How to do that? I have on clue about that.
Your relationships are a little screwed up, you probably want to change those. Note the hasMany() vs the belongsTo(). If a something can only have one user, you may wish to change the function to hasOne() from hasMany() and the name of the function to user() only because it makes more sense that way.
class Something extends Eloquent {
protected $table = 'something';
public function users()
{
return $this->hasMany('User', 'id_something');
}
}
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $table = 'something_users';
protected $hidden = array('password', 'remember_token');
public function something()
{
return $this->belongsTo('Something', 'id_something');
}
}
And then to save a something and a user and have them linked, it's pretty easy.
$something = new Something;
$something->name = Input::get('name');
$something->url = Input::get('url');
$something->save();
$user = new User;
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$something->users()->save($user);
I'm not seeing your constructor so I don't know which model $this->db refers to, but you may want to replace the somethings or users depending on what you have. To keep your dependency injection going, I'd suggest naming your dependencies what they actually are.
class SomeController extends BaseController {
public function __construct(User $user, Something $something)
{
$this->user = $user;
$this->something = $something;
}
public function someFunction()
{
$this->something->name = Input::get('name');
$this->something->url = Input::get('url');
$this->something->save();
$this->user->email = Input::get('email');
$this->user->password = Hash::make(Input::get('password'));
$this->something->users()->save($this->user);
}
}
Laravel 6.
I want to add data to users table and customer table using one controller that is RegisterController.
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Customer;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
//this part is my code
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'role' => '2',
]);
$customer = Customer::create([
'user_id' => $user['id'],
'firstname' => $data['name'],
'lastname' => $data['name'],
'email' => $data['email'],
'address' => '',
'phone' => '',
'gender' => '',
]);
return $user;
}
}
enter image description here
enter image description here
This answer is not the best one, because this answer is just a shortcut code so that my code is not error. maybe another error will appear in the future.
but I hope my answer can solve your problem

Categories