Replies: 3 comments 1 reply
-
Alternatively, they just add a shortcut to use Illuminate\Support\Stringable;
Stringable::macro('random', fn($length = 16) => tap($this, ($stringable) => $stringable->value = Str::random($length));
(new Stringable)->random()->lower(); |
Beta Was this translation helpful? Give feedback.
-
I'm not convinced on stringable-first policy, as my little usual string handling can more easily be solved with the string helpers. There is another unmentioned solution already available, although not as elegant, it is definitely short: str(Str::random())->lower(); The result shaedrich achieved is somewhat elegant, like: |
Beta Was this translation helpful? Give feedback.
-
I have opened a PR #48612 to add the |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Proposal
Change the
Str::random()
method to return an instance ofStringable
instead of a string to allow fluent chaining.Example
Backwards Compatibility
Since the
Stringable
class implements the magic__toString()
method this should have minimal impact to existing code. However, there is a chance for breakage if type hinting or comparing against a type ofstring
.The following are some of the situations I predict would cause issues.
However updating code could be as simple as declaring a type on creation.
Background
Recently I had the need to generate random strings in the format of
xxxx-xxxx-xxxx-xxxx
(all lowercase) and came up with thisThis works fine but it's a mix of Laravel
Str
helpers and native PHP methods. So I tried to use fluent strings to make this more expressive and readable.This had two issues.
First, the
split()
method doesn't work the same asstr_split()
. For this I opened a PR to add thechunk()
method to theStringable
class. That was merged today.The second issue is the reason for this idea. That is, the
Str::random()
method is not chainable.If this idea is accepted and merged the following would become possible.
If there is interest I will do the work and open a PR.
Beta Was this translation helpful? Give feedback.
All reactions