Framework: Fluent Strings doesn't work with each() function.

Created on 17 Dec 2020  路  5Comments  路  Source: laravel/framework


  • Laravel Version: 8.18.1
  • PHP Version: 8.0.0
  • Database Driver & Version: 10.4.17-MariaDB

Description:

Fluent Strings doesn't work with each() function.

Steps To Reproduce:

return User::take(2)->get()->each(function(User $user) {
    $user->emailOnly = Str::of($user->email)->before('@');

    return $user;
});

Result

image

Work Fine

return User::take(2)->get()->each(function(User $user) {
    $user->emailOnly = Str::before($user->email, '@');

    return $user;
});

Result

image

All 5 comments

It works fine but you can not use Fluent strings in that fashion.

Take a look in Str class on L50. The of method returns a new Stringable class. On L741 there is a __toString() method.

You should call toString() at the end.

return User::take(2)->get()->each(function(User $user) {
    $user->emailOnly = Str::of($user->email)->before('@')->__toString();

    return $user;
});

@filkris L108 Before function return string.

Example:

public function index()
{
    return Str::of('[email protected]')->before('@');
}

It's work fine without __toString().
image

You can't compare the 2 exactly the same.

Fluent implements JsonSerializable and Jsonable so the response is converted to json. And since Stringable is an object it return {}.

Stringable by itself just an object. So it got converted to string from the Response object.

https://github.com/laravel/framework/blob/7365e4459c2ef048ea9cfe23f515b73695549f92/src/Illuminate/Routing/Router.php#L764-L787

See the above.

Thanks guys for explanation. @crynobone @driesvints @filkris

Was this page helpful?
0 / 5 - 0 ratings

Related issues

felixsanz picture felixsanz  路  3Comments

PhiloNL picture PhiloNL  路  3Comments

Anahkiasen picture Anahkiasen  路  3Comments

progmars picture progmars  路  3Comments

ghost picture ghost  路  3Comments