Is the "Casting" feature ($casts) valid only using Eloquent in Laravel [duplicate] - laravel

This question already has answers here:
How to change format of created_at and updated_at in laravel Model?
(2 answers)
Closed 12 months ago.
I try to use $casts to change date format in my Model :
protected $casts = [
'created_at' => 'datetime:Y-m-d H:i',
'updated_at' => 'datetime:Y-m-d H:i'
];
It works when I retrieve the data with Eloquent :
$clients = Client::all();
return $clients;
but it doesn't with Query Builder !
$clients = DB::table('clients')->get();
return $clients;

In query builder you are using DB::table it does not use Laravel Model and you are writing this casts code to your Laravel Model. It obviously never work. They are apples and oranges.
If you use casts code, Laravel only runs this code when you get the model and use this field. Before that it does not change the values.
What are you trying to achieve there? If you give us more detailed code I will help you.

Related

Laravel Passport API Response

When I requested by Laravel Passport API then my datetime data has been changed like first Photo.
Second Photo is Laravel Model Casting.
Third one Photo is my table column.
How I get my original data without Laravel Mutator (Accessor)
I need always return my app timezone wise data with format Y-m-d H:i:s
Have any way to handle it easily?
Try Like below. It will solve your problem.
protected $casts = [
'email_verified_at' => 'datetime:Y-m-d H:i:s',
'mobile_verified_at' => 'datetime:Y-m-d H:i:s',
];

Can not format datetime in laravel 7.2.2

i am currently working in laravel 7.2.2 and I am trying to format following datetime in to 'M d Y' .
"created_at": "2020-03-23T12:17:29.000000Z",
Previously, in laravel 6, datetime formats are like this: 2019-12-02 20:01:00.
but now, date format is changed, and appearing like above: 2020-03-23T12:17:29.000000Z.
In laravel 6 i used to format my datetime as following code:
foreach ($posts as $post) {
$createdAt = Carbon::parse($post['created_at']);
$post['created_at'] = $createdAt->format('M d Y');
}
But it gives me same output as above 2020-03-23T12:17:29.000000Z .
So, how can i format my datetime in laravel 7.
Any help?
This was a breaking change introduced in Laravel 7.0. You can still format it the way you want.
You can override the serializeDate method on your model:
/**
* Prepare a date for array / JSON serialization.
*
* #param \DateTimeInterface $date
* #return string
*/
protected function serializeDate(DateTimeInterface $date)
{
return $date->format('M d Y');
}
See the docs in the upgrade guide for more information.
HTH
You can use Eloquent resources to transform the data from your model to what the API should respond with. That way you won't need to touch the data and how the data is saved in your model.
It could look like something like this, given that your column names are the same:
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Http\Request;
class Post extends JsonResource
{
public function toArray(Request $request)
{
return [
'id' => $this->id,
'title' => $this->title,
'text' => $this->text,
'created_at' => $this->created_at->format('M d Y'),
'updated_at' => $this->updated_at->format('M d Y'),
];
}
}

In laravel how do I fetch date as date instead of datetime format?

In my database some fields are set as date, while others are datetime or timestamp formats. However when fetching data, the "date" fields are also shown with the 00:00:00 time string attached at the end. How can I prevent this?
You can use date/datetime casting with an additional format parameter as described in the Eloquent: Mutators documentation.
class User extends Model
{
protected $casts = [
'created_at' => 'datetime:Y-m-d',
];
}
This will apply the given format when serializing the model to an array or json. If you want to use a different format in your blade templates, you can use the format() function on the datetime property you want to change:
{{ $user->created_at->format('Y-m-d') }} or {{ $user->created_at->toDateString() }}
You will have to add the created_at column to the $dates property of your model though:
protected $dates = [
'created_at',
];
This basically adds 'created_at' => 'datetime' to your $casts.

Datetime on blade laravel

How to get month name on blade laravel ?
i tried this but the result is the month number
$training->date_activity->month
as per the documentation of Carbon, your approach is correct.
http://carbon.nesbot.com/docs/#api-getters
Yet it could be the property is not considered a Carbon DateTime.
Can you make sure that in the Training Model you have 'date_activity' as a date mutator?
protected $dates = [
'created_at',
'updated_at',
'date_activity'
];

Simplify store controller method on laravel 5

This is my store method to save a post.
public function store(CreatePostRequest $request)
{
$post = new Post([
'title' => $request['title'],
'content' => Crypt::encrypt($request['content']),
'published_at' => Carbon::now()
]);
$post->user()->associate(Auth::user());
$newPost=Post::create($post->toArray());
$this->syncTags($newPost, $request['tag_list']);
return redirect('posts')->withMessage('Post Saved Successfully !!!');
}
In laracasts tutorial he is just doing a
Article::create($request->all());
I need to do the extra stuff like encrypt, but am i cluttering the method? could it be cleaner?
Do it in the Model. I use the set/get*Attribute() method to change stuff on the fly.
So you could use Article::create($request->all()); then in the model use the fillable array to only autofill what is allowed (such as title, content and published_at).
then use something like (in the model)
function setContentAttribute( $value ){
$this->attributes['content'] = Crypt::encrypt($value);
}
In fact you could also adapt this approach so that the published_at attribute is set to today, or even better use your database to provide now()s time.

Resources