Laravel One to One relation error don't know why? - php

Error Showing
Symfony\Component\HttpFoundation\Response::setContent(): Argument #1 ($content) must be of type ?string, Illuminate\Database\Eloquent\Relations\HasOne given, called in G:\Laravel\practice-1\vendor\laravel\framework\src\Illuminate\Http\Response.php on line 72
User Model
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* #var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function book()
{
# code...
return $this->hasOne(Book::class);
}
}
Book Migration
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateBooksTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('books', function (Blueprint $table) {
$table->id();
$table->integer('user_id')->unsigned();
$table->string('title');
$table->string('abut');
$table->float('amount', 8, 2);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('books');
}
}
Route::get('/user/{id}/book', function ($id) {
return User::find($id)->book();
});
I have no idea why I am seeing this error. I have also looked at the documentation but no help was found.

Your definitions are good. But this statement:
return User::find($id)->book();
returns a Illuminate\Database\Eloquent\Relations\HasOne object.
That is no valid content for a response. Try to change it to:
return User::find($id)->book;

Related

Laravel 9 Eloquent relations with UUID

why the user_id is set to ? in Eloquent hasOne relation's sql query
"select * from `files` where `files`.`user_id` = ? and `files`.`user_id` is not null",
here's the model code
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable implements MustVerifyEmail
{
use HasApiTokens, HasFactory, SoftDeletes,HasUuids;
/**
* The attributes that are mass assignable.
*
* #var array<int, string>
*/
protected $fillable = [
'name',
'email',
];
protected $keyType = 'string';
public $incrementing = false;
/**
* The attributes that should be hidden for serialization.
*
* #var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
'id'=>'string',
];
public function profile_picture(){
return $this->hasOne(File::class);
}
}
and the file model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class File extends Model
{
use HasFactory,HasUuids;
protected $fillable = [
'name',
'content',
'extension',
];
protected $keyType = 'string';
public $incrementing = false;
public function user(){
return $this->belongsTo(User::class);
}
}
migrations:
Schema::create('users', function (Blueprint $table) {
$table->uuid('id')->primary()->unique();
$table->string('name');
$table->string('email');
$table->softDeletes($column = 'deleted_at', $precision = 0);
$table->rememberToken();
$table->timestamps();
});
Schema::create('files', function (Blueprint $table) {
$table->uuid('id')->primary()->unique();
$table->string('name');
$table->string('extension');
$table->uuid('user_id')->nullable();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
Instead of using auto-incrementing integers as your Eloquent model's primary keys, you may choose to use UUIDs instead. UUIDs are universally unique alpha-numeric identifiers that are 36 characters long.
code php explain the problem and the corect code.

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'majors.user_id' in 'where clause' (SQL: select * from `majors` where `majors`.`user_id` = 1

I want to display user's major. I've defined relationship between user-major and i created foreignId 'major_id' in user's table. I migrated all migrations successfully. But when i want to display user's major it return error
SQLSTATE[42S22]: Column not found: 1054 Unknown column
'majors.user_id' in 'where clause' (SQL: select * from majors where
majors.user_id = 1 and majors.user_id is not null limit 1)
model Major.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Major extends Model
{
use HasFactory;
// protected $primaryKey = 'info_id';
protected $guarded=['id'];
public function faculty(){
return $this->belongsTo(Faculty::class);
}
public function user(){
return $this->belongsTo(User::class);
}
}
model User.php
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array<int, string>
*/
// protected $fillable = [
// 'name',
// 'email',
// 'password',
// ];
protected $guarded=['id'];
/**
* The attributes that should be hidden for serialization.
*
* #var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function getRouteKeyName()
{
return 'name';
}
public function score(){
return $this->hasMany(Score::class);
}
public function major(){
return $this->hasOne(Major::class);
}
}
2021_05_21_042431_create_majors_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateMajorsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('majors', function (Blueprint $table) {
$table->id();
$table->foreignId('faculty_id')->constrained();
$table->string('nama_jurusan');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('majors');
}
}
2022_05_22_000000_create_users_table.php
<?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->id();
$table->unsignedBigInteger('major_id');
// $table->foreignId('major_id')->constrained('majors');
$table->foreign('major_id')->references('id')->on('majors');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->bigInteger('nrp');
$table->string('address');
$table->integer('generation');
// $table->string('major');
// $table->string('faculty');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
index.blade.php to display user's major
#extends('dashboard.layouts.main')
#section('container')
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
<h1>Biodata</h1>
{{-- <h1 class="h2">Welcome back, {{auth()->user()->name}}</h1> --}}
{{-- <div class="btn-toolbar mb-2 mb-md-0"> --}}
</div>
<div class="container">
<h4>Nama: {{auth()->user()->name}}</h4>
<h4>Email: {{auth()->user()->email}}</h4>
<h4>Alamat: {{auth()->user()->address}}</h4>
<h4>Angkatan: {{auth()->user()->generation}}</h4>
<h4>Jurusan: {{auth()->user()->major->nama_jurusan}}</h4>
<h4>Fakultas: {{auth()->user()->major->faculty->nama_fakultas}}</h4>
</div>
#endsection
in the user modal change the relationship to
public function major(){
return $this->belongsTo(Major::class);
}
And When select write
User::with('major')->get();
I think what you have done till is right need to add proper fillable value in models.
you user model should be like this
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
'major_id',
'nrp',
'address',
'generation'
];
protected $guarded=['id'];
/**
* The attributes that should be hidden for serialization.
*
* #var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function getRouteKeyName()
{
return 'name';
}
public function score(){
return $this->hasMany(Score::class);
}
public function major(){
return $this->hasOne(Major::class,'id','major_id');
}
}
Note : Laravel default conventions are looking user_id on majors table but its not there thats the issue for this case so add your convention to user model like this
public function major(){
return $this->hasOne(Major::class,'id','major_id');
}

How I migrate from laravel to my database

I'm trying to create a migration to add tables and columns to my database and all I get is this error.
PHP Fatal error: Cannot declare class CreateJuegosTable, because the name is already in use in C:\xampp\htdocs\2020-21-DAW2-M12-Royal-Dice\database\migrations\2021_05_10_000000_create_juegos.php on line 7
this is the code I'm trying to run:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateJuegosTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('juegos', function (Blueprint $table) {
$table->id();
$table->string('juego');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('juegos');
}
}
This is the file names, I changed and the error still there
This is the model
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, 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',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
check migrations and rename if any exists with the name "Juegos". if refactor/rename does not work open the migration and rename directly.... then run below command to clear cache
php artisan optimize
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateJuegosTable---(rename this)---- extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('juegos'---(rename this)----, function (Blueprint $table) {
$table->id();
$table->string('juego');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('juegos'----(rename this)----);
}
}

PHP Recoverable fatal error: Object of class could not be converted to string

Getting : "PHP Recoverable fatal error: Object of class Database\Factories\RoleFactory could not be converted to string in C:\Users\kk\Desktop\imageupload\iu\database\factories\RoleFactory.php on line 25"
when executing this :
Role::factory()->count(5)->make();
Role.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
use HasFactory;
public function users(){
return $this->belongsToMany('App\Models\user');
}
}
User.php
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, 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',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function users(){
return $this->belongsToMany('App\Models\role');
}
}
RoleFactory.php
<?php
namespace Database\Factories;
use App\Models\Role;
use Illuminate\Database\Eloquent\Factories\Factory;
class RoleFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* #var string
*/
protected $model = Role::class;
/**
* Define the model's default state.
*
* #return array
*/
public function definition()
{
return [
'name'=>$this->faker->JobTitle
];
}
}
UserFactory.php
<?php
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class UserFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* #var string
*/
protected $model = User::class;
/**
* Define the model's default state.
*
* #return array
*/
public function definition()
{
return [
'name' => $this->faker->name(),
'email' => $this->faker->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
];
}
/**
* Indicate that the model's email address should be unverified.
*
* #return \Illuminate\Database\Eloquent\Factories\Factory
*/
public function unverified()
{
return $this->state(function (array $attributes) {
return [
'email_verified_at' => null,
];
});
}
}
Create_roles_table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateRolesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('roles');
}
}
create_role_user_table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateRoleUserTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('role_user', function (Blueprint $table) {
$table->id();
$table->foreignId('role_id')->constrained()->onDelete('cascade');
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('role_user');
}
}

Use of undefined constant when seeding

I get this error when trying to seed my database with php artisan db:seed:
[ErrorException] Use of undefined constant username - assumed 'username'
I've checked the Laravel docs and the syntax looks correct, however I'm not sure what I'm messing up on this.
<?php
class DatabaseSeeder extends Seeder {
/**
* Run the database seeds.
*
* #return void
*/
public function run(){
Eloquent::unguard();
$this->call('UsersTableSeeder');
}
}
class UsersTableSeeder extends Seeder {
public function run(){
User::create([
'username' => 'Ziggy',
'email' => 'ziggy#stardust.com',
'password' => '1234'
]);
}
}
EDIT: I've added the User model:
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 {
public $timestamps = false;
protected $fillable = [username, password];
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');
}
Here is the migration file used:
<?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('username');
$table->string('email')->unique();
$table->string('password');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('users', function(Blueprint $table)
{
Schema::drop('users');
});
}
}
In User class, change this:
protected $fillable = [username, password];
to this
protected $fillable = ['username', 'password'];
The way it has been declared, PHP took them as constants and not strings

Categories