Why is Laravel eloquent returning empty - laravel

This is my model
namespace App\Models\Invitation;
use App\Models\Model;
class SendtoType extends Model
{
}
When i get data from SendtoType it return empty or null but i sure sendto_types table has datas
$types = SendtoType::all();
dd($types); // return empty collection
$types = SendtoType::find(1);
dd($types);// null
It's happend after i run php artisan command:reset_table sendto_types command.
I cleared cache but it's not working.

Thank you everyone, i found my mistake:
i set timestamp for table's deleted_at column but forgot to set not null so it also filled deleted_at column when i add data.
That's why eloquent clause return empty.
So silly mistake!

You can add protected $table = 'sendto_types'; inside your model class with actual table name in your database.
class SendtoType extends Model
{
protected $table = 'sendto_types';
}

Command command:reset_table is not a built in command, so you'd need to look at your source code to see what it does, but by the name of it, I would assume the command empties your table.
In this case, your table is empty, so your query will not return any results.

Related

Laravel Eloquent firstOrCreate doesn't work properly

I'm used to it but today this problem makes me weak..;;
class Market {
// ..
public function ttl()
{
return $this->ttlRelation()->firstOrCreate(
['market_id' => $this->id],
['tier' => 0, 'direction'=>0]
);
}
}
The Market model has one TTL model. I know that firstOrCreate method finds an item as first given array and if it doesn't exists create a new one as persist, returns it.
Besides, its mass-assignment so I filled up $fillable property on ttl model..
class TradingTacticalLayer extends Model
{
public $timestamps = false;
protected $fillable = ['direction', 'tier'];
}
..and I'm getting SQLSTATE[HY000]: General error: 1364 Field 'direction' doesn't have a default value (SQL: insert into "trading_tactical_layer_test" ("tier", "market_id") values (0, 1)) message. I cannot understand why this method won't filled up insert field list proper way. I expect, if I edit $fillable property as ['direction'], SQL would implode ("direction") as insert field and it doesn't.
In general, from my experience, I just set those fields as nullable or manually set a default value. At this time, I want to know why this weird happens and what am I doing wrong.
Well, probably, optimize:clear solve the problem.
I still don't know what makes this error but if you experience mismatch between $fillable property and inserting field list, optimize:clear is an option anyway..

Why eloquent doesn't return error on diffrent primarykey?

I was working on an old database which primarykey is 'Id'. Eloquent set up the primary key to default 'id', so it is little change, but still can be confusing. Of course I didnt notice that, and I wanted to save updated models to database. There was no error, and $model->save() return was good but database didn't update. Furthermore I have other functions that get models from the database, and they work as they should without overriding $primarykey.
So here is my question: Why isn't eloquent returning any warnings or errors ? Of course I found in the documentation that I should override $primarykey in the model, and then everything worked perfectly.
I was using MySql 10.1.16-MariaDB.
Here is Laravel controller
public function update(Request $request, Order $order)
{
$order->fill($request->get('data'));
$order->save();
$order->products;
return $order;
}
Vue.js function
editOrder () {
this.fullscreenLoading = true
axios.put('/web/' + this.url + '/' + this.rowId, {'data': this.row})
.then(({data}) => {
this.row = data;
this.fullscreenLoading = false
});
},
Laravel Model was standard, of course my model is now properly updated, when i got this problem there was no $primarykey, I didnt mention $fillable and relationship to products but in my project they are defined and working.
class Order extends Model
{
use LogsActivity;
protected $table = 'orders';
protected $primaryKey = 'Id';
protected $fillable = []
}
If you execute the query with get(), create() or similar method, it will work as before because Eloquent doesn't use PK in this case. But some methods like find() will not work for you until you setup $primaryKey property in the model.
You didn't get an error because there was no error.
When you ran $order->save(), the query generated would have been something like:
update `orders` set `field1` = ?, `fieldN` = ?, `updated_at` = ? where `id` is null
This is a perfectly valid SQL statement, and when it runs, it would produce no errors. However, it will also not update any records (unless you do have a record where the id is null).
The reason why the update query is using null is because your Order model does not have an id attribute, it has an Id attribute, and PHP array keys are case-sensitive. So, when Laravel attempts to get the value for the id attribute, it returns null, and uses that in the query.

Eloquent set updated_at value with creating. Ho can fix it?

In Eloquent when instantiating the model established by the two timestamps - created_at and updated_at with the same values. But according to the logic when you create a label should be established whether the created and the label is updated the next time you upgrade. How to fix it?
Eloquent 5.2, created_at and updated_at in db is integer (protected $dateFormat = 'U')
UPDATE - when I use the method, the properties created_at and updated_at is still updated at the same time. That is the first action - the creation, are set equal. The second action - update. Again, both fields are updated and they have the same value.
This is how Laravel does things sometimes, not letting the updated_at null is also a way to avoid problems with not null constraints. But you can fix that for you, if you please. You probably will be able to do something like this:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model as Eloquent;
class BaseModel extends Eloquent
{
public function save(array $options = [])
{
$saved = parent::save($options);
if ($this->wasRecentlyCreated) {
$this->updated_at = null;
parent::save($options);
}
return $saved;
}
}
And use this BaseModel in all your models

Laravel 5 > touch pivot table (Many-to-Many)

Why is the updated_at field in my pivot table not updating giving the following setup?
Model
class Conversation extends Model {
public function users()
{
return $this->belongsToMany('App\User')->withTimestamps();
}
}
Controller
$conversation = Conversation::find($id);
$conversation->users()->touch();
The last line should - as far as I understand the whole thing - also update the pivots table updated_at field, shouldn´t it?
But it isn´t. Right now I have to do it manualy via a DB query.
I think the best way to do this is:
$conversation->users()->updateExistingPivot(
$conversation->users()->get(),
['updated_at' => date('Y-m-d H:i:s')]
);
It works for me (Laravel 5.7).

Many-to-Many and Eager loading query

I am new with Laravel, I was able to query Many-to-Many relationships. Where 'template_dynamic' is the pivot of two tables 'template' and 'dynamic'.
// Template Model
class Template extends Eloquent
{
protected $table = 'template';
protected $guarded = array('template_id');
protected $primaryKey = 'template_id';
public function dynamic()
{
return $this->belongsToMany('dynamic', 'template_dynamic')
->select('*')
->withPivot('template_dynamic_id')
->orderBy('template_dynamic_html_sort', 'ASC');
}
here I was able to retrieve the records
// Template Controller
$dynamic_fields = Template::find($rec->template_id)->dynamic;
what I want to do now is that pivot table has-many properties 'template_dynamic_option'. How will I query the records and combine it with $dynamic_fields variable?
// What I want to do is something like this. But sadly this is an invalid syntax
$dynamic_fields = $dynamic_fields->with('template_dynamic_option');
Any recommendation or enhancements are welcome.
Thank you in advance.
First, I am pretty sure you don't need the select('*') in your relationship query there.
But let's get to your actual problem ;)
To access the pivot table in Eloquent is pretty simple.
$dynamic_fields = Template::find($rec->template_id)->dynamic;
foreach($dynamic_fields as $dynamic){
var_dump($dynamic->pivot)
}
The thing is though, by default only the keys of the pivot table are present in the object.
To change that you have to define them with withPivot(). Actually like you already did but not with the id.
public function dynamic()
{
return $this->belongsToMany('dynamic', 'template_dynamic')
->withPivot('template_dynamic_option')
->orderBy('template_dynamic_html_sort', 'ASC');
}
And if you have multiple additional columns use this syntax:
->withPivot('template_dynamic_option', 'foo', 'bar');

Resources