Laravel model create() and fill() methods doesn't work - php

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.

Related

Why is the value of the 'id' column of the database showing null?

I am using laravel 6.I have created a table called 'student', where the value increment of the 'id' column is supposed to happen but is not happening.
This is my migration file:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateStudentsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('students', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email');
$table->bigInteger('phone');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('students');
}
}
In my students table:
My StudentController file:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Student;
class StudentController extends Controller
{
public function student()
{
return view('student.create');
}
public function index()
{
$student = Student::all();
return view('student.index', compact('student'));
}
public function store(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|max:50|min:5',
'phone' => 'required|unique:students|max:12min:9',
'email' => 'required|unique:students',
]);
$student = new Student;
$student->name = $request->name;
$student->email = $request->email;
$student->phone = $request->phone;
$student->save();
$notification = array(
'message' => 'Data Insert Done!',
'alert-type' => 'success'
);
return Redirect()->route('all.category')->with($notification);
// DB::table('student')->insert($data)
// return response()->json($student);
}
public function ViewStudent()
{
}
}
Model file:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
protected $fillable = [
'id','name', 'email', 'phone',
];
}
There is a possibility that you are working with a database whose schema was set for the students table either manually (not through migration, but, for example, by executing an SQL query where auto-increment was not set), or after applying the migration, the auto-increment was removed.
Because your migration code is written correctly according to the official Laravel documentation for the method increments(string $attribute):
I see two solutions here:
change a table column via SQL query so that it matches the description in the migration
ALTER TABLE students CHANGE id id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY;
or the same using phpmyadmin or IDE tools;
generate a schema using your migration (php artisan migrate --path=database/migrations/..._create_students_table.php), but for this preliminarily you need to save the students table data, for example, to a dump.
Since you are using phpmyadmin, look at the settings for the id attribute in the students table.
The only reason I can think of is if you did something like this in your model:
/**
* Indicates if the IDs are auto-incrementing.
*
* #var bool
*/
public $incrementing = false;
If so then it should be set to true or removed entirely.
Second, make sure your id is guarded in your model like so:
/**
* The attributes that aren't mass assignable.
*
* #var array
*/
protected $guarded = ['id'];
This way you avoid mass assignments.
Judging by your controller code, I assume the error lies somewhere in the line where you grab an instance of your student model
Change
$student = new Student;
To
$student = new Student();
You need a new instance of a specific model in order to insert a new id, please post your current model code also.
Sample model code.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Product extends Model
{
use SoftDeletes;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'product_bar_code', 'product_name', 'product_image', 'product_price'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = ['created_at', 'updated_at', 'deleted_at'];
}
Maybe something is wrong with the way you have written your model code.

How can i get data using Eloquent Relationships in laravel

I need to get data from the teaching_subjects table to my Vue file according to teacher table data. I have created the relationship with the TeachingSubject model and Teacher model.
This is my Teacher Model,
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Teacher extends Model
{
protected $table = 'teacher';
protected $fillable = [
'firstName',
'lastName',
'teacherUserName',
'contactNo',
'teacherEmail',
'gender',
'teaching_expirence',
'Qualifications',
'description',
'speakEnglish',
'speakJapan',
'password',
'status',
];
public function approvalStatus(){
return $this->belongsTo(ApprovalStatus::class);
}
public function teachingSubject(){
return $this->hasMany(Teacher::class);
}
}
And this is my TeachingSubject Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class TeachingSubject extends Model
{
protected $table = 'teaching_subjects';
protected $fillable = [
'teacher_id',
'subject_id',
'lesson_fee'
];
public function teacher(){
return $this->hasMany(Teacher::class);
}
public function subject(){
return hasMany(Subject::class);
}
}
This is my Subject model,
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Subject extends Model
{
protected $table = 'subject';
protected $fillable = [
'subject',
'grade_id',
'no_of_teachers',
'status'
];
public function teachingSubject(){
return belongsTo(TeachingSubject::class);
}
}
This is my Teching_subjects migration file
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTeachingSubjectsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('teaching_subjects', function (Blueprint $table) {
$table->integer('id')->unsigned()->autoIncrement();
$table->integer('teacher_id')->unsigned();
$table->integer("subject_id")->unsigned();
$table->float("lesson_fee")->nullable();
$table->timestamps();
$table->foreign('teacher_id')
->references('id')->on('teacher');
$table->foreign('subject_id')
->references('id')->on('subject');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('teaching_subjects');
}
}
I need to get the date(created_at), teacher_name, lesson and lesson_fee using TeachingSubjectController.
for example if You want to get user that made the comment, so get that user from the comment object.
Try this
$user = User::find(1);
$posts = $user->posts;
foreach ($posts as $post) {
foreach ($post->comments as $comment) {
echo $comment->commentcontent;
echo $comment->users;
}
}

How to use 'get' method with the where eloquent in laravel

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.

Relation one to many it doesn't work

https://imgur.com/a/ob9rjIz
There are two tables one called user and another called user_relation_user
My relation is an user to many user_relation_user and in my migration. I want to create 10 user with php artisan tinker so i run factory(App\User::class, 10)->create(); at the end i access to my database so do select * from users there are 10 users but in user_relation_user isn't 10 id or it's empty
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Administrator extends Model
{
protected $table = 'user_relation_user';
protected $primaryKey = 'id';
protected $fillable = ['user_id'];
public function users(){
return $this->belongsTo(User::class,'user_id');
}
}
<?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 = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function administrator(){
return $this->hasMany(Administrator::class,'user_id');
}
}
//hasMany
My migration
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUserRelationUserTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('user_relation_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('user_id_admin')->unsigned();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*foreign
* #return void
*/
public function down()
{
Schema::dropIfExists('user_relation_user');
}
}
The relation you define is correct,you just need to define a relation in user model as well.
Example:
Suppose you are developing a blog system where user can post blogs.
then there will be two models user model and blog model
In User model you have to define user relation as below:
public function blogs()
{
return $this->hasmany(Blog::class);
}
Then in blogs model
public function users()
{
return $this->belongsTo(User::class);
}

Laravel 5.3 Does protected variables in a Model act as constructor

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

Categories