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.
Related
right now i am stuck in this not really knowing what to do (maybe is really easy, but i don't see how to do it).
I have this model of users:
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
protected $table = 'tcn_user';
// Time for the relations
public function user(){
return $this->morphTo(__FUNCTION__, 'type_user', 'id_user');
}
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'username','permision', 'first_name', 'surname', 'us_password', 'email'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'us_password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Being the problem (I suppose) in the function user(). I call it but it returns null when doing it, the variables for the childs are there, so I really don't know what is wrong. But for doubts I have here the code for one of them so you can see it.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Teacher extends Model
{
protected $table = 'teacher';
//In first place let's do the relations of the model
public function user(){
return $this->morphOne(User::class, 'user', 'id_user');
}
public function schedule(){
return $this->hasMany(ServiceSchedule::class, 'id_teacher');
}
public function session(){
return $this->hasMany(DaySession::class, 'id_teacher');
}
}
Being the important one the function user().
If you need for information please let me know, is my first time asking here, so i really don't know if I am doing it well.
PD: Okey, sorry for the things i have forgotten to add.
This being to code about how i am calling the Teacher:
public function detail($id){
$user = User::find($id);
if(is_object($user)){
$data = array(
'code' => 200,
'status' => 'success',
'user' => $user,
'subuser' => $user->user
);
}else{
$data = array(
'code' => 404,
'status' => 'error',
'message' => 'El usuario no existe'
);
}
return response()->json($data);
}
And the relation it have, well, we have User, the parent "class" with the information all the users need to have, and after that we have the "childs" like Teacher, Student, Parent, all of then with different information.
And responding to Rwd, no, i don't have a camp in the database with the name user, is more, the table user is named tcn_user (Because user is a keyword in mysql)
I get an error when create a table seeder using model factory in laravel 8 but I don't know where I'm going wrong here.
This is an error:
Undefined constant "App\Models\boolean"
at C:\xampp\htdocs\mason\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Factories\Factory.php:628
Here is my code:
Category.php:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Astrotomic\Translatable\Translatable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Category extends Model
{
use HasFactory, Translatable;
protected $with = ['translations'];
protected $translatedAttributes = ['name'];
protected $hidden = ['translattions'];
protected $casts = ['is_active' => boolean];
protected $fillable = ['parent_id', 'slug', 'is_active'];
}
CategoryFactory.php:
<?php
namespace Database\Factories;
use App\Models\Category;
use Illuminate\Database\Eloquent\Factories\Factory;
class CategoryFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* #var string
*/
protected $model = Category::class;
/**
* Define the model's default state.
*
* #return array
*/
public function definition(): array
{
return array(
'name' => $this->faker->word(),
'slug' => $this->faker->slug(),
'is_active' => $this->faker->boolean(),
);
}
}
CategoryTableSeeder.php
<?php
namespace Database\Seeders;
use App\Models\Category;
use Illuminate\Database\Seeder;
class CategoryTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
Category::factory(10)->create();
}
}
At Eloquent: Mutators & Casting we can read:
The $casts property should be an array where the key is the name of the attribute being cast and the value is the type you wish to cast the column to.
It doesn't mention having constants defined, though you can figure out given that one of the possible values listed is decimal:<digits>, which isn't a valid constant name.
Also, the example shown is:
protected $casts = [
'is_admin' => 'boolean',
];
I am trying to get my project to use authorization roles to restrict users to certain featuers and I am following along with a tutorial. When I make a call to a class in my user.php file I am getting an error that the class App\Role can't be found. I am not sure if it is a namespace issue but I can't get to the bottom of it. I believe it is the roles function that is giving me this issue.
<?php
namespace EliteWorker;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'address', 'phone', '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 roles() {
return $this->belongsToMany('App\Role');
}
public function hasAnyRoles($roles){
return null !== $this->roles()->whereIn('name', $roles)->first();
}
public function hasAnyRole($role){
return null !== $this->roles()->where('name', $role)->first();
}
}
You changed the namespace to EliteWorker so if the Model class Role is generated with Artisan, it'll also have that namespace
public function roles()
{
return $this->belongsToMany('EliteWorker\Role');
}
Note that you can also get the model base name by calling the class static property
public function roles()
{
return $this->belongsToMany(Role::class);
}
No need to import it if it's in the same namespace
Also note that the artisan command app:name has been removed in Laravel 6 to encourage developers to use the generic App namespace
I wanted to relate a profile model to the existing user model using the relationship belongs to and hasOne and I am getting that error.
here is my Profile.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
public function user(){
return $this->belongsTo(User::class);
}
}
User.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Symfony\Component\HttpKernel\Profiler\Profile;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'username', '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);
}
}
In my terminals i can get the user through the profile but cannot get the profile using user. here is the error
$user->profile
TypeError: Too few arguments to function Symfony/Component/HttpKernel/Profiler/Profile::__construct(), 0 passed in /Users/macair13/freeCodeGram/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php on line 720 and exactly 1 expected.
To fix the issue, replace the use Symfony\Component\HttpKernel\Profiler\Profile; line on top of your User.php file with use App\Profile; instead.
This is happening as you've mistakenly included the wrong class on top of your User.php file. When Laravel is trying to load the relationship, it attempts to construct a Symfony\Component\HttpKernel\Profiler\Profile object instead of constructing your intended model.
Use like below in your user model
public function profile()
{
return $this->hasOne('App\Profile', 'foreign_key');
}
I am not sure why you have used Symfony\Component\HttpKernel\Profiler\Profile in your user model. When your relationship is building it is using that Profile and not your Profile Model. You have to use the Profile Model namespace while defining the relationship.
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',
);
}