n Create Custom Collections in Laravel | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh

Create Custom Collections in Laravel


First of all we need to create a custom collection. I typically create a directory called Collections in /app.



namespace App\Collections;

use Illuminate\Database\Eloquent\Collection;

class PostsCollection extends Collection
    public function toDropdown($key = 'id', $value = 'title')
        return $this->keyBy($key)->map(function ($post) use ($value) {
            return $post->getAttribute($value);


Now, we just need to tell the eloquent model that we want to use this collection instead of the default Illuminate\Database\Eloquent\Collection.


namespace App;

use App\Collections\PostCollection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class Post extends Model
    public function newCollection(array $models = [])
        return new PostCollection($models);

Once we've added the hook above, we can use this collection in our controller like so.


namespace App\Http\Controllers;

use App\Post;

class RelatedPostsController extends Controller
    public function index()
        $postOptions = Post::query()
            ->toDropdown('id', 'title');

        return view('related-posts.create', compact('postOptions'));

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts


Page Facebook