-1

In laravel 9.0 this code worked well and then I could use $result->property syntax in my blade view instead of array syntax $result['property']

    public function getAllWithPaginator($perPage = null)
    {
        $columns = ['title','slug','category_id', 'image', 'fulltext', 'created_at'];
        $categoryColumns = 'category:id,title,slug,image';

        $result = $this
            ->startConditions()
            ->wherePublished(true)
            ->select($columns)
            ->with($categoryColumns)
            ->orderBy('created_at', 'DESC')
            ->get()
            ->toArray();

        $result = Arr::arrayToObject($result); 
        $result = collect($result)->mypaginate($perPage);

        return $result;

    }

Now in Laravel 12 this gives error Method Illuminate\Support\Arr::arrayToObject does not exist. How I can do it now? Maybe Arr::arrayToObject was removed from framework to external package or there is another way to do it?

4
  • Are you sure arrayToObject function exists in laravel? Maybe you've modified the vendor file to add the function? I've checked the laravel/framework repository and found no such method on v9's release. Commented Oct 30 at 4:46
  • 1st think is ->get() do give you the object(Illuminate\Database\Eloquent\Collection), no need for ->toArray(). 2nd try to use inbuilt pagination of laravel. You are getting all rows from database then doing the pagination, that will affect the performance. Commented Oct 30 at 4:59
  • ->get() outputs "heavy" object, whereas ->toArray() contains only pure data. Commented Oct 30 at 10:51
  • then why use Eloquent query in 1st place? its much slower than raw query Illuminate\Support\Facades\DB Commented Oct 30 at 15:01

1 Answer 1

1

Arr::arrayToObject() isn’t a Laravel method (and wasn't in Laravel 9 either). You likely had a custom helper or a package that added it. In any case, you don’t need it here, just stop converting your models to arrays.

The reason $result->property worked is because Eloquent models are objects. When you call ->toArray() you throw that away. In Laravel 12 just keep the query returning models and use the built-in paginator.

return $this->startConditions()
    ->wherePublished(true)
    ->select($columns)
    ->with(['category:id,title,slug,image'])
    ->latest('created_at')
    ->paginate($perPage); 

Then in your blade you can loop into it :

@foreach ($result as $item)
  {{ $item->title }}
  {{ $item->category?->title }}
@endforeach

{{ $result->links() }}
Sign up to request clarification or add additional context in comments.

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.