Search code examples
laravelstdclass

How to extract information from stdClass object?


In the build function of my Mailable I extract information from a database like so:

$this->data = DB::select('select * from newsletter_mails order by id desc limit 1')[0];

\Log::info(print_r($this->data, true));

$this->subject = $this->data->subject;
$this->content = $this->data->content;

\Log::info(print_r($this->subject, true));
\Log::info(print_r($this->content, true));

which yields the log:

[2021-11-13 15:49:41] production.INFO: stdClass Object
(
    [id] => 2
    [from] => test@test.com
    [subject] => testSubject
    [content] => testMessage
    [file] => 
    [created_at] => 2021-11-13 15:49:10
    [updated_at] => 2021-11-13 15:49:10
)
  
[2021-11-13 15:49:41] production.INFO: testSubject  
[2021-11-13 15:49:41] production.INFO: testMessage  

As you can see data variable is a stdClass Object and the information gets extracted correctly. But now I want to get the from value:

$this->from = $this->data->from;

\Log::info(print_r($this->from, true));

This outputs two things in the log. First the correct output for $this->form:

[2021-11-13 15:55:25] production.INFO: test@test.com  

But also an error:

[2021-11-13 15:55:25] production.ERROR: Cannot access offset of type string on string {"userId":1,"exception":"[object] (TypeError(code: 0): Cannot access offset of type string on string at C:\\Users\\Artur\\PhpstormProjects\\stuttard.de\\vendor\\laravel\\framework\\src\\Illuminate\\Mail\\Mailable.php:360)
[stacktrace]

What am I doing wrong?


Solution

  • You store the data in $this->data property and also overriding all other properties of the Mailable class.

    You should store the data from the database in a local variable like this:

    $data = DB::select('select * from newsletter_mails order by id desc limit 1')[0];
    $from = $data->from;
    
    \Log::info(print_r($from, true));