I was trying to get all the elements sharing a common row data
but I keep getting this error I do not know why
Call to a member function get() on null
Here is the code I used, I have imported the App\User and everything but still not getting it and I have a user in my table with that role_id
My controller
<?php
namespace App\Http\Controllers;
use App\Animal;
use App\Clinic;
use App\Role;
use App\Slaughter;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ClinicController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$farms = User::where('role_id', 3);
$user = Auth::user();
$animal = Animal::all();
return view('clinic.index', compact('user', 'animal', 'farms'));
}
My user table
<?php
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->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->unsignedBigInteger('address_id')->index();
$table->unsignedInteger('role_id');
$table->string('description')->nullable();
$table->timestamps();
$table->foreign('address_id')->references('id')->on('addresses');
});
}
But I am keep getting that error bellow I do not know the why
use App/User;
$farm = User::where('role_id', 3)->get();
Try below code for getting the record
$farm = User::select(['id','name'])->where('role_id', 3)->get();
In case the User class extends Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model{}
calling
$builder = User::where('role_id', 3);
always returns an object of type Illuminate\Database\Eloquent\Builder, therefore, calling
$user= User::where('role_id', 3)->get();
always returns a collection (which might be empty when there is no user with role_id = 3). Check the type of your User class.
I think there are some missed steps that you didn't take.
The User does not refer to the table name but to the model class name. So first things first you need to create a model.
In order to do that you use the command:
php artisan make:model User
If you want a dedicated Models folder(i always use one) you use
php artisan make:model Models/User
By that time you should have a model created but you need to set it up.
Going inside your User.php file you should have something like this:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes that are NOT mass assignable.
*
* #var array
*/
protected $guarded = [
'created_at', 'updated_at', 'password,
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
//
];
}
Now by including your model at the top of your file you can use your Model class.
Related
I have the following model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Review extends Model
{
protected $fillable = ['*'];
public $dates = ['page_available_untill'];
public static function findByUUID(string $uuid): self|null
{
return self::where('page_uuid', $uuid)->get()->first();
}
}
Model seeder:
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
public function run()
{
Review::create([
'page_uuid' => ReviewUUIDGenerator::generate(),
'order_id' => 10000
]);
}
}
Migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateReviewsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('reviews', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->integer('order_id');
$table->string('page_uuid');
$table->dateTime('page_available_untill')->nullable();
$table->integer('operator_speed')->nullable();
$table->integer('operator_quality')->nullable();
$table->integer('operator_politeness')->nullable();
$table->integer('master_arrival_speed')->nullable();
$table->integer('master_work_quality')->nullable();
$table->integer('master_politeness')->nullable();
$table->enum('materials_quality', ['Хорошее', 'Плохое', 'Не устанавливали'])->nullable();
$table->enum('would_recommend', ['Да', 'Нет', 'Затрудняюсь ответить'])->nullable();
$table->double('payment_summ', 9, 2)->nullable();
$table->text('comment')->nullable();
$table->json('photos')->default(json_encode([]));
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('reviews');
}
}
Basically the model stores a review info for a given job (let's say for example my job is to help people make some documents and after my job is done i ask my clients to submit a review to my job)
The problem is:
when i set $fillable = ['*']; i can access model attributes like an object properties, BUT i cant create a new model or fill model with some model attributes if i don't hard code needed properties to $fillable like $fillable = ['page_available_untill', 'order_id', 'etc'] is that how it acually works or i don't understand something?
protected $guarded = [];
Replace protected $fillable = ['*']; by protected $guarded = [];
protected $fillable = ['*'];
this please enter column name in fillable, for example
protected $fillable = ['page_uuid','order_id'];
Add column name in fillable and let me know if its working or not
In eloquent ORM, $fillable attribute is an array containing all those fields of table which can be filled using mass-assignment.
Mass assignment refers to sending an array to the model to directly create a new record in Database.
Refer this
https://laravel.com/docs/9.x/eloquent#mass-assignment
You can't use * in fillable method. You have to add all needed column in the fillable.
The migrations file look like below
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('title')->unique();
$table->text('body');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
but the posts table in the database is having 0 as value.
The database is populated through the web.php code below. I need the user_id to have values 1 and 2 in the database posts.
Route::get('/create',function (){
$post=Post::create(['title'=>'lara vel','body'=>'laravel is good for php','user_id'=>1]);
$post=Post::create(['title'=>'spri ng','body'=>' spring is good for java','user_id'=>2]);
});
It's very Simple
just Go to your Post model
when you use create method to insert data you must be use fillable propery in your model.
so if you not have an Post model so create post Model and paste this code inside your Post Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $table = 'posts';
protected $fillable = [
'user_id', 'title','body'
];
}
I'm new to Laravel & Eloquent, I'm coming from Django.
In Django I can create a filter on my results and use an object to filter the results...
I'm trying to figure out if I could do this in Laravel/Eloquent also...
Here's what I'm trying to do....
create_messages_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMessagesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('messages', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('user_id');
$table->string('message');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('messages');
}
}
Message.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Message extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
MessageController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Message;
use Illuminate\Support\Facades\Auth;
class MessageController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$messages = Message::where("user", Auth::user())->get();
dd($messages);
return $messages;
}
}
The problem is that when the controller index() function is routed too... I get an error saying "user" column does not exist... and it doesn't but I assumed the models user() function would take care of that and that I would be able to compare it's returning object with Auth::user().
Am I wrong, or am I just doing it wrong?
In the "where" query, the first parameter must be a column in the database. If you want to make use of a "user" column, I'll suggest you add a user column to your table.
I think the auth:user() is to authenticate the current user.
So laravel eloquent is only alerting you that the "user" column does not exist. I will suggest you create a user column, and see what happens next.
I'm new to Laravel and I noticed some are similar to Java, some aren't. I guess it's because it uses OOP style.
I'm following a video tutorial for beginners and came across the protected modifier (if I'm correct).
I originally learned programming in Java. Below are three php file definitions.
Does the protected $fillable in the Product class act like a constructor in Java which requires you to supply values before you can create an instance of the class? (in this case, Product Class)
ProductTableSeeder.php
<?php
use Illuminate\Database\Seeder;
class ProductTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$product = new \App\Product([
'imagePath' => 'someImagePathURL',
'title' => 'Harry Potter',
'description' => 'Super cool - at least as a child.',
'price' => 10
]);
$product->save();
}
}
Product.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $fillable = ['imagePath','title','description','price'];
}
create_products_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('imagePath');
$table->string('title');
$table->text('description');
$table->integer('price');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('products');
}
}
The line $product = new \App\Product I understand to be the instantiation part.
I'd appreciate any useful explanation to this.
Thank you.
protected $fillable = ['imagePath','title','description','price'];
It means, the field names that are given in this array can only be inserted into database from our side. Like, it is only allowed to fill values from us.
In clear, referred from document.
The $fillable property means an array of attributes that you want to be mass assignable
And,
The $guarded property means an array of attributes that you do not want to be mass assignable
Reference : https://laravel.com/docs/5.3/eloquent#mass-assignment
So I'm trying a basic php artisan db:seed after migrating my database but it keeps returning the title error in cmd -[Symfony\Component\Debug\Exception\FatalErrorException] Class 'User' not found
Things I Have Tried
php dump-autoload after updating the class
php dump-autoload before running the db:seed function
rolling back the migration and then re-running it
rolling back the migration and then re-running it with the --seed syntax
Change the namespace of the 'Users' File
Below is the migrations
<?php
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');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('users');
}
}
I believe that everything here is correct, and now here is the user class.
<?php namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['name', 'email', 'password'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
}
And now lastly is the all important database seeder
<?php
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
Model::unguard();
// $this->call('UserTableSeeder');
$this->call('UserTableSeeder');
Model::reguard();
}
}
class UserTableSeeder extends Seeder
{
public function run()
{
DB::table('users')->delete();
User::create(['email' => 'John#doe.com']);
}
}
So that's it my full syntax, if any more files are required then please request them and I will update my question.
In your DatabaseSeeder in the root namespace you call the Class User. It therefor tries to load the class User. The definition of your class User is however in namespace App. You should therefor use either App\User in your DatabaseSeeder or add at the top of the file use App\User;
DatabaseSeeder
<?php
use App\User;
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
Model::unguard();
// $this->call('UserTableSeeder');
$this->call('UserTableSeeder');
Model::reguard();
}
}
class UserTableSeeder extends Seeder
{
public function run()
{
DB::table('users')->delete();
User::create(['email' => 'John#doe.com']);
}
}
Since Laravel 8+ the User class is now stored by default in the app/Models directory; so instead of using App\User use App\Models\User above.
Ps. by default Laravel ships with a User model, use that one. In case you removed that model you can use the fallback provided by Laravel:
use Illuminate\Foundation\Auth\User;
On a side note something I find very useful in order to debug artisan output. You should use the flag -vvv which adds extreme verbosity to the output messages including a complete stack trace.
php artisan migrate -vvv