در حال بارگذاری ...

Reviewing Eloquent casting0:00

No doubt you're familiar with casting in Eloquent. If I take a look at the casts property on this User model, you can see that emailVerifiedAt is automatically converted to date time, password is automatically hashed, and in this particular case I have two custom casts, settings and achievements, which use the asCollection and asEnumCollection casts respectively. Now we have to do this little bit of jockeying with the string concatenation colon syntax in order to specify a custom collection and the enum that we're interested in using. You may note that there's actually a pretty cool using method available on asCollection so that we could specify settings collection class like so instead of using string concatenation. But if you attempt to use it, well, your IDE is going to throw an absolute error because

Switching to casts method0:48

so that we could specify settings collection class like so instead of using string concatenation. But if you attempt to use it, well, your IDE is going to throw an absolute error because you're not allowed to use that kind of class syntax inside properties. To rectify this, Laravel 11 allows you to define a protected casts method. So let's create that, protected function casts returns an array, and I'll take everything we have in the cast property here and I'll simply return it inside the casts method instead, and now I can completely remove this property from the User model. And you'll see that all of the problems that were plaguing us before have disappeared. In fact, why don't we update asEnumCollection as well using the of method, passing in the achievement fully qualified class name.

Cleaning up custom casts1:29

In fact, why don't we update asEnumCollection as well using the of method, passing in the Achievement fully qualified class name. I can now remove the string concatenation workaround and I end up with a much cleaner casts array. I'll say that this is a completely opt in feature. So when you upgrade to Laravel 11, you don't need to go and make this change right away. But I do think it's far cleaner than what we've had to do in the past.

دوست دارید گاهی خبرهای Laracasts را ایمیل کنیم؟