Two Types of Collections in Laravel

Lynn Lin
Lynn Lin
May 15, 2017 · 3 min read

The key is whether we are using eloquent data or not

For type hint of PHP 7

<?phpnamespace App;use App\Post;
use Illuminate\Support\Collection as BaseCollection;
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
class PostRepository
{
private $model;
public function __construct(Post $post)
{
$this->model = $post;
}
public function popular(): BaseCollection // EloquentCollection
{
return $this->model
->select(['title', 'summary', 'pageview'])
->orderBy('pageview', 'desc')
->limit(3)
->get();
}
}

For unit test

<?phpnamespace Tests\Unit;use Tests\TestCase;
use App\PostRepository;
use Illuminate\Support\Collection as BaseCollection;
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
class PostRepositoryTest extends TestCase
{
public function testPopular()
{
$repo = $this->app->make(PostRepository::class);
$result = $repo->popular();
$this->assertInstanceOf(BaseCollection::class, $result);
$this->assertInstanceOf(EloquentCollection::class, $result);
$this->assertEquals(collect(), $result); // Fail
}
}

Make the return type consistent


Lynn Lin

Written by

Lynn Lin

Backend Developer

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade