PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, January 13, 2022

[FIXED] Return Laravel options() as array when no optional parameter has been provided

 January 13, 2022     laravel     No comments   

Issue

Laravel has the super handy optional() helper.

I would like to combine it with a custom Model attribute like this:

// this method is on the User model
public function getDataAttribute()
{
    // this data comes from another service
    $data = [
        'one' => 1,
        'two' => 2,
    ];

    return optional($data);
}

So I can use it like this:

$user->data->one // 1
$user->data->two // 2
$user->data->three // null

However, I am also trying to return the entire array by doing:

dump($user->data); // this should dump the internal $data array

But this will return an instance of Illuminate\Support\Optional with a value property.

Illuminate\Support\Optional {#1416 ▼
  #value: {#2410 ▼
    +"one": 1
    +"two": 2
  }
}

Is it possible to return the original $data array if no "sub"parameter (= a child attribute of $user->data) is given? Or is there a possibility to detect a child parameter in the getDataAttribute()?

I hope it's clear what I am trying to achieve.


Solution

Thanks to lagbox for pushing me in the right direction. I have solved this by using the following macro:

Illuminate\Support\Optional::macro('toArray', function()
{
    return (array) $this->value;
});

This way I can access all data by using:

$user->data->toArray();


Answered By - santacruz
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing