Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel String helper returns object

Tags:

laravel

When I do this:

$test = Test::create([
  'email' => Str::of($this->email)->trim(),
]);

dd($test->toArray());

I get this:

array:14 [▼
  "email" => Illuminate\Support\Stringable {#669 ▼
    #value: "[email protected]"
  }
]

The problem is that I'm passing $test to an event, and in that event $event->test->email is empty when I for instance send it in a Slack notification. I'm guessing because it's an object and not a string?

I know that I can use PHPs trim(), but I have some more complex Str helpers that I chain which is really helpful. How can I make sure the end result is a string and not an object of Stringable?

Preferably directly when using Str::of($this->email)->trim(), and not for instance doing something like public string $email; in the event because as indicated I use multiple parameters and don't want to convert them all separately.

like image 390
eskimo Avatar asked Mar 06 '26 03:03

eskimo


1 Answers

Try to cast it as string using (string) or __toString() like

$test = Test::create([
  'email' => (string)Str::of($this->email)->trim(),
]);
$test = Test::create([
  'email' => Str::of($this->email)->trim()->__toString(),
]);
like image 186
mmabdelgawad Avatar answered Mar 08 '26 01:03

mmabdelgawad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!