Date field must cast to 'date' in Eloquent model - laravel

Hi I'm using laravel nova for create an admin panel. And I'm trying to use Date Field.
This is my migration,
$table->date('day')->nullable();
This is my my nova resource,
public function fields(Request $request)
{
return [
ID::make()->sortable(),
Date::make(__('Day'), 'day'),
];
}
This is my model,
class Menu extends Model
{
use HasTranslations;
public $translatable = ['name','description'];
protected $fillable = [
'name','description','typology', 'cost', 'day', 'active', 'buffet'
];
This is my error,
Date field must cast to 'date' in Eloquent model.
Do I need to do anything in resource ?

In your model class you just need to add the following lines which describe to laravel that you must cast the day field into a date object (Carbon):
//Casts of the model dates
protected $casts = [
'day' => 'date'
];
Check here someone has the same issue.
EDIT:
I have seen that your day column is set to nullable i think that your field Nova should be to like in this post :
public function fields(Request $request)
{
return [
ID::make()->sortable(),
Date::make(__('Day'), 'day')->nullable(),
];
}
And we need to change the model like this,
protected $casts = ['day' => 'date'];

Related

Format date before query database: casts and mutatores

The front end of my application consumes the following date format: d-m-Y h:m:s
To achieve this , I use protected $casts in the model:
protected $casts = [
'created_at' => 'datetime: d-m-Y h:m:s',
'updated_at' => 'datetime: d-m-Y h:m:s',
];
Works well (for output).
The problem is when, for example, I want to get data from the database within a date range.
In this case, the date is sent to the server side in the following format 01-02-2022.
For the query to work correctly, the date must previously be in the format 2022-02-01.
I tried to solve it with a mutator, but it is not working.
use Illuminate\Support\Carbon;
protected $fillable = [
...
'created_at'
];
public function setCreatedAtAttribute($value)
{
$this->attributes['created_at'] = Carbon::createFromFormat('d-m-Y', $value)->format('Y-m-d');
}
This is a common design pattern for me, as Laravel conveniently allows us to overload newQuery() in a 'BaseModel' class, and extend from this class in all our other Models:
you may Override Illuminate\Database\Eloquent\Model 's query()!
/**
* Overrides Illuminate\Database\Eloquent\Model 's query()
*
* #return mixed
*/
public function newQuery($excludeDeleted = true)
{
$query = parent::newQuery($excludeDeleted)->where('created_at',$this->getCreatedAt());
return $query;
}

How to create a data associatively? laravel eloquent

I have a Post model:
class Post extends Model
{
protected $fillable = [
'title',
'user_id',
'token',
'body'
];
public function favorites()
{
return $this->hasMany(Favorite::class);
}
public function addFavorite($state = 1)
{
$this->favorites()->create(compact('state'));
}
}
Favorite model:
class Favorite extends Model
{
protected $fillable = ['user_id', 'post_id', 'state'];
}
When I test in tinker:
$post = Post::first();
$post->addFavorite();
It returns me an error below:
Illuminate/Database/QueryException with message 'SQLSTATE[HYOOO]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into favorites...
Why it ask user_id when it is given in the post? Question is do I necessarily need to input the user_id to achieve this?
The question of whether user_id is necessary is up to you. Will it come in handy later on? Does having it on the posts table suffice?
It is asking for user_id because you do not have a default value field on that field in the favorites table. You can either set a default value, remove it from the table (if you decide you don't need it), OR provide it when creating via the relationship:
class Post extends Model
{
protected $fillable = [
'title',
'user_id',
'token',
'body'
];
public function addFavorite($state = 1)
{
$this->favorites()->create([
'state' => $state,
'user_id' => $this->user_id,
]);
}
public function removeFavorite()
{
$this->addFavorite(0);
}
}
Don't forget to include the relationship definition of favorites on the Post model.
Based on the plural name, it seems that a post has many favorites, but then your removeFavorite() method calls the addFavorite method?? This would not actually remove anything - it would create a new record.
Since Favorite model is related to Post model and you create it via relation()->create(), you can skip specifying post_id as Laravel can deduce it. But you do have to specify user_id, because there's no way for your code to know that favourite.user_id and post.user_id is the same. So in short: yes, you have to specify user_id.

Laravel alias column name in Eloquent model

How can I alias a column name in a model? I would like to show idUser instead of id in API responses. So far I've tried the following.
protected $maps = [
'id' => 'idUser',
];
protected $visible = [
'idUser'
];
protected $appends = [
'idUser'
];
This gives me an error:
'Call to undefined method App\User::getIdUserAttribute()'
Also, I would like to alias created_at and updated_at to createdAt and updatedAt.
you can define accessor method in your model like this :
public function getUserIdAttribute($)
{
return $this->id;
}
and then you have to add the attribute name in the $appends array
protected $appends = ['user_id'];
for more details checkout the docs
https://laravel.com/docs/5.8/eloquent-mutators
As #Namoshek's comment, you should be able to return a custom aliases for each column by renaming it.
First, look for which route you want to edit in folder routes/api.php. You can either use callback function or a Controller to manage the response.
// routes/api.php
Route::middleware('auth:api')->get('auth/retrieve-user', function(Request $request) {
$user = Auth::user();
return response()
->json([
'userId' => $user->id,
'createdAt' => $user->created_at,
'updatedAt' => $user->updated_at,
]);
});

Laravel Relationship Without Timestamps

Is there away to call a model with a relationship without timestamps when calling the with statement in the model itself - instead of going into that relationship model and saying $protected timestamps = false;
e.g
class Post Extends Eloquent {
public function template() {
return $this->hasOne('App\Template', 'id', 'template_id')->timestamps(false);
}
}
You can add this in following model to skip the values
protected $hidden = [
'created_at',
'updated_at'
];

How to apply $casts converting to pivot column with manyToMany relationships in laravel 5.3?

I have problem with apply $casts to pivot column in laravel 5.3. I using manyToMany relationships.
My 3 DB tables:
users - contain: id,…other columns
books - contain: id,…other columns
book_user (pivot table) - contain: book_id, user_id, options
“options” is JSON type.
I want use $casts to converting my pivot column options to json_encode/json_decode.
Example:
$casts = ['pivotColumn.options'=>'array']
My models:
class User extends Model
{
protected $casts = [
books.pivot.options' => 'array',
];
public function books() {
return $this->belongsToMany('App\Book’)->withPivot('options');
}
}
class User extends Model
{
protected $casts = [
users.pivot.options' => 'array',
];
public function books() {
return $this->belongsToMany('App\User’)->withPivot('options');
}
}
I found that the version 5.1 and higher you can use dot notation for pivot casts.
Example:
protected $casts = [
books.pivot.options' => 'array',
];
I tried more variant but nothing. It is not working :/.
Can you help me please?
Thank you for each answer.

Resources