1

My Eloquent query is:

$postcode = address::where('client_id', $bill->client_id)->where('label', $bill->location)->select('postcode')->get();

echo $postcode returns[{"postcode":"LS18 2DY"}]

How to I return just the postcode string?

$postcode->postcode or $postcode['postcode'] fail

0

3 Answers 3

3

[{"postcode":"LS18 2DY"}] is array of object.

Since you used ->get() you're returning more than one item that will be wrapped into array.

Restrict it to one item ->first()

$postcode = address::where('client_id', $bill->client_id)->where('label', $bill->location)->select('postcode')->first();

A second way, would be

$postcode[0]->postcode 

I would recommend to use first() instead of adding index.

Check Laravel documentation for retrieving a single row

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

Comments

0

get() returns an array, you should use the get(1) or first() to get one element, or foreach to triverse the array.

$postcode = address::where('client_id', $bill->client_id)->where('label', $bill->location)->select('postcode')->get(1);
$postcode->postcode;

1 Comment

same result: Undefined property: Illuminate\Database\Eloquent\Collection::$postcode
0

convert the collection object to an array using toArray() then access each single data using foreach

$data = some collection;

foreach($data->toArray() as $single_data)
{
    echo $single_data['key for each data'];
}

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.