laravel eloquent Array to string conversion

16.5k Views Asked by At

I building a helper in laravel to return a single field from eloquent.

class Helper {

    public static function getAddress($id) {
        //intval($id);
        $result = DB::table('tableaddress')
            ->where('id',$id)
            ->pluck('address');

        //dd($result);
        return $result;

    }
}

In the view i'm calling it via {!! Helper::getAddress(112233) !!} but getting an error of Array to string conversion.

Here is if the result of dd

enter image description here

How do I get the address to return a string. Thanks

3

There are 3 best solutions below

12
On BEST ANSWER

You need to get first result from an array, so use this:

->pluck('address')[0];
2
On

You can try it as:

{!! Helper::getAddress(112233)->first() !!}

Or add first directly in your helper function as:

$result = DB::table('tableaddress')
           ->where('id',$id)
           ->pluck('address')
           ->first();
0
On

You need to loop through the returned result from Helper::getAddress(112233)