1

I'm trying to do something like this:

$variable = Model::where($data)->get();

$data is stored in the database as ['type' => 1, 'status' => 2]

I cannot seem to be able to parse the data from a string to array properly, the best I have gotten close to is

0 => "['type' => 1, 'status' => 2]"

How can I properly parse this array from DB -> variable in php?

4
  • 1
    That’s not a deserializable format. You should write a custom parser for it, but that particular string can be evaluated: $array = eval("return $data;"); Commented Sep 26, 2021 at 8:57
  • 2
    It would be better if you changed the way the data is stored and used something like JSON instead. Commented Sep 26, 2021 at 9:06
  • @rickdenhaan - oh yeah noted thank you. Commented Sep 26, 2021 at 9:10
  • @NigelRen - I agree, thank you, JSON would be easier to manage actually Commented Sep 26, 2021 at 9:10

1 Answer 1

1

I managed to fix it using the following:

$data = "['type' => 1, 'status' => 2]";
$variable = Model::where(eval("return $data;"))->get();

This will work properly.

Cleaned and Updated as @rickdenhaan recommended.

Sign up to request clarification or add additional context in comments.

1 Comment

Just a quick note: if you're defining $data yourself like here in this code sample, it's best to avoid eval() and just write $data = ['type' => 1, 'status' => 2]; (without the " marks), then $data will already be an array. This is basically what eval() is doing with your string anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.