Laravel’s AsStringable cast transforms model attributes into Stringable objects, providing fluent access to Laravel’s powerful string manipulation methods directly from your model attributes.
When working with text in your Laravel models, you often need to perform various string operations like formatting, cleaning, or transforming the text. While you could do this manually each time, Laravel’s AsStringable cast transforms your model’s string attributes into powerful Stringable objects, giving you access to dozens of built-in string manipulation methods.
This cast is particularly useful when you consistently need to perform string operations on specific model attributes. Instead of writing the same string manipulation code repeatedly, you can access these operations directly on your model attributes as if they were Stringable objects.
use IlluminateDatabaseEloquentCastsAsStringable;
class Post extends Model
{
protected $casts = [
'title' => AsStringable::class,
'content' => AsStringable::class,
];
}
Let’s explore a practical example of a blog system with SEO-friendly content handling:
<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentCastsAsStringable;
class Article extends Model
{
protected $casts = [
'title' => AsStringable::class,
'content' => AsStringable::class,
'meta_description' => AsStringable::class
];
public function getSlugAttribute()
{
return $this->title
->lower()
->replaceMatches('/[^a-z0-9s]/', '')
->replace(' ', '-')
->limit(60, '');
}
public function getSeoTitleAttribute()
{
return $this->title
->title()
->limit(60, '...')
->append(' | My Blog');
}
public function getExcerptAttribute()
{
return $this->content
->stripTags()
->words(50, '...')
->title();
}
public function getReadingTimeAttribute()
{
return $this->content
->stripTags()
->wordCount() / 200;
}
}
The AsStringable cast simplifies string manipulation by providing a fluent interface for common text operations, making your code more readable and maintainable.
The post String Manipulation Made Easy with Laravel’s AsStringable Cast appeared first on Laravel News.
Join the Laravel Newsletter to get all the latest
Laravel articles like this directly in your inbox.
Source: Read MoreÂ