0

I have a database query as below:

$data = DB::table('settings')->select('value')->where('name', '=', $name)->get();
        echo $data["value"];

but it gives error:

Undefined index: value

if I echo $data; then I get below result:

[{"value":"theme_default"}] 

3 Answers 3

1

get() returns a Laravel Collection object, which has magic methods to turn itself into a string when you try to use it as such (like with an echo statement). As you can see in the JSON that you've printed, $data is an array or collection of objects, so you want the first one in the collection before trying to get the value:

$row = $data->first();
echo $row->value;
Sign up to request clarification or add additional context in comments.

1 Comment

oh now I understand. but echo $row->value worked echo $row['value'] gives me error "Cannot use object of type stdClass as array" ..
1

Try this:

$data = DB::table('settings')->select('value')->where('name', '=', $name)->first();
echo $data["value"]; 
//or
echo $data->value; 

Comments

0

You can turn the result into an array like this:

$data = DB::table('settings')
            ->select('value')
            ->where('name', '=', $name)
            ->get()
            ->toArray();
//then use the value of the first element
dd(@$data[0]['value']);

, but I strongly suggest that you use the Laravel Collection in order to make use of its powerful methods.

Comments

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.