Laravel Eloquent Saving Behavior - laravel

Is it normal behavior that Laravel requires you to save a parent model before saving a hasMany relationship? I am able to use belongsTo before the model is saved.
$team = new Team();
$team->tournament()->associate($tournament);
// $team->save(); without this line, it will throw an error
$team->players()->save(new TeamPlayer([
'user_id' => 1
]));
$team->save();
The Team model's relationships looks like this:
public function players()
{
return $this->hasMany(TeamPlayer::class);
}
public function tournament()
{
return $this->belongsTo(Tournament::class);
}
The error that is thrown is this
Integrity constraint violation: 1048 Column 'team_id' cannot be null (SQL: insert into `team_players` (`user_id`, `team_id`, `updated_at`, `created_at`) values (1, , 2017-12-18 13:32:29, 2017-12-18 13:32:29))

Related

Laravel's UUID (introduced in 9.3) throwing some errors for Users

I recently decided to upgrade to Laravel 9.3 (from 9.1). I wanted to take advantage of the UUID introduced by 9.3 and get rid of my custom UUID trait. So now my models use:
use HasUuids;
So far so good. But I noticed that my Users table was using an autoincrement PK so I decided to use UUID in there as well. To do so I changed the migration to be:
Schema::create('users', function (Blueprint $table) {
$table->uuid('id')->primary();
...
But now when I try to register a new user:
$hashedPassword = Hash::make($data->password);
$userToRegister = new RegisterUserData(
$data->name,
$data->email,
$hashedPassword,
);
$user = User::create($userToRegister->toArray());
return $user->getAuthToken();
I'm getting back the following error:
"message": "SQLSTATE[01000]: Warning: 1265 Data truncated for column 'tokenable_id' at row 1 (SQL: insert into `personal_access_tokens` (`name`, `token`, `abilities`, `expires_at`, `tokenable_id`, `tokenable_type`, `updated_at`, `created_at`) values (auth_token, bbd7ff53780a9a4e1e922a03e7c7bd2ae23f8043ba809d19392cf1e9f91a357c, [\"*\"], ?, 97c75f9d-e2cd-4d40-8fb2-8947854dd89d, Domain\\Shared\\Models\\User, 2022-11-19 02:39:44, 2022-11-19 02:39:44))",
"exception": "Illuminate\\Database\\QueryException",
"file": "/Users/hansgruber/Desktop/webdev/projects/dundermifflin-be/vendor/laravel/framework/src/Illuminate/Database/Connection.php",
It is a warning so the User is being still created but don't know where this is coming from. Furthermore, if I try to login that existing user I'm getting something similar:
{
"status": false,
"message": "SQLSTATE[01000]: Warning: 1265 Data truncated for column 'tokenable_id' at row 1 (SQL: insert into `personal_access_tokens` (`name`, `token`, `abilities`, `expires_at`, `tokenable_id`, `tokenable_type`, `updated_at`, `created_at`) values (auth_token, 32a157db020baca42fce009373d807d9154be108505792a5138dbfa457c4a631, [\"*\"], ?, 97c75ed4-4264-4875-a3b6-6985d3080943, Domain\\Shared\\Models\\User, 2022-11-19 02:39:01, 2022-11-19 02:39:01))"
}
the login function in the controller is:
public function login(UserData $userData): JsonResponse
{
try {
if (!Auth::attempt($userData->toArray())) {
return response()->json([
'message' => "invalid credentials",
])->setStatusCode(Response::HTTP_UNAUTHORIZED);
}
$user = User::where('email', $userData->email)->first();
return response()
->json([ 'data' => $user->getAuthToken()])
->setStatusCode(Response::HTTP_OK);
} catch (\Throwable $th) {
return response()->json([
'status' => false,
// todo: log the actual error but return a custom one to avoid giving away system details.
'message' => $th->getMessage()
], Response::HTTP_INTERNAL_SERVER_ERROR);
}
}
any idea what's going on?

Polymorphic model only working on one model

I currently have a polymorphic relationship using a model like so:
The model is called Productable
In the model I have:
public function productable()
{
return $this->morphTo();
}
I have another model called Product that has access to the Productable model like so:
public function productDetails()
{
return $this->morphMany(Productable::class, 'productable');
}
This works as expected and I can create a record in the Productable table like so:
$p = new Product;
$p->product_name = $request->product_name;
$p->product_type = $request->product_type;
$p->category_id = $request->product_category;
$p->description = $request->product_description;
$p->save();
$p->productDetails()->create([
'product_id' => $p->id,
]);
However the issue is I have another model called Media
which also has:
public function productDetails()
{
return $this->morphMany(Productable::class, 'productable');
}
On that model I attempt to write a record like so:
$pMedia = new Media;
$pMedia->productDetails()->create([
'product_id' => $p->id,
'productable_id' => $value,
]);
The error I get is:
Integrity constraint violation: 1048 Column 'productable_id' cannot be null (SQL: insert into `productables` (`product_id`, `productable_id`, `productable_type`, `updated_at`, `created_at`) values (38, ?, App\Models\Media, 2021-03-04 18:46:51, 2021-03-04 18:46:51))
What am I doing wrong here? Shouldn't I be to write to Media in the same way? I'm wondering what I'm missing.

how to sync() method additional pivot table Laravel

i have pivot table call user_privilege,
user_id,
privilege_id
house_group_id,
i use method sync for store data into pivot tabl, this is my method
$data = $this->getCollectedData($getListCollectData, $viewType, $data);
$getData = $this->crud->store($data);
$getData->getPrivilege()->sync([
'user_id' => $getData->id,
'house_group_id' => $this->request->get('house_group_id'),
'privilege_id' => 3,
]);
this is my getPrivilege() method in Users Model
public function getPrivilege()
{
return $this->belongsToMany(Privilege::class, 'user_privilege', 'user_id', 'privilege_id', 'house_group_id');
}
but when i click submit, return error like this
SQLSTATE[HY000]: General error: 1364 Field 'house_group_id' doesn't have a default value (SQL: insert into `user_privilege` (`privilege_id`, `user_id`) values (b3f08343-a8f6-4a45-b7bc-b396125634d3, ?))
when i dd($this->request->get('house_group_id')) return ID house_group_id like this
"2539d741-1526-4c42-b57a-da60e2e862d8"
this is UUID from house_group_id,
Whats wrong in My Code, how to save data with addtional pivot table ?
thanks

Why am I getting the error in post? Laravel

So I'm trying to create a simple REST API using Laravel.
While testing out the API with creating new items to the database I'm receiving an error:
Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (world.cities, CONSTRAINT cities_ibfk_1 FOREIGN KEY (CountryCode) REFERENCES country (Code)) (SQL: insert into cities (Name, CountryCode, District, Population, updated_at, created_at) values (Valhalla, vlh, Ragnar Alley, 200000000, 2020-02-19 01:07:26, 2020-02-19 01:07:26)) in file C:\xampp\htdocs\myapp\vendor\laravel\framework\src\Illuminate\Database\Connection.php on line 669
here's the Controller:
public function createCity(Request $request) {
$city = new City;
$city->Name = $request->Name;
$city->CountryCode = $request->CountryCode;
$city->District = $request->District;
$city->Population = $request->Population;
$city->save();
Model:
class City extends Model
{
protected $table = 'cities';
protected $fillable = ['Name', 'CountryCode', 'District', 'Population'];
}
Help would be appreciated as I can't figure out why I'm getting the error after POST.
Thanks in advance.
You try to add vlh as contry_code value into your model .but this field refrence to another model that have country name and in that table there is not any record with this condition and vlh value is unknown or it.
You can romve relation between these models (if it is possible) or first find the id of country that has that code and then insert it into your model.

Laravel - Many to Many Polymorphic Relation with Extra Fields

How can I define a many to many polymorphic relation with extra fields?
I have three (or more, as it is a polymorphic relation) tables.
tags table: id, name
tagged table: id, tag_id, taggable_id, taggable_type, user_id
posts table: id, record, timestamps
users table: id, name, email
The user_id on the tagged table referes to the users table on column id.
In my Post model I have:
public function tags()
{
return $this->morphToMany('App\Tag', 'taggable','tagged');
}
and in my Tag model I have:
public function posts()
{
return $this->morphedByMany('App\Post', 'taggable','tagged');
}
Then when I am try this in my controller:
$tag = new \App\Tag(
array(
'tag'=>"someTag"
));
$tag->save()
$post = \App\Post::find($id);
$post->tags()->save($tag);
I get Integrity Constraint Violation for not having a user_id:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (hb.tagged, CONSTRAINT tagged_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id)) (SQL: insert into tagged (tag_id, taggable_id, taggable_type) values (26, 2, App\Resource)).
Which is somewhat expected, as I have never had the chance to define or declare the user_id field.
Also, I have tried withPivot() on tags relation as follows, to no avail:
public function tags()
{
return $this->morphToMany('App\Tag', 'taggable','tagged')->withPivot('user_id');
}
Like in the comment: withPivot has nothing to do with saving/creating. If you want to pass additional pivot data when saving, do this:
$post->tags()->save($tag, ['user_id' => $userId]);

Resources