Skip to content

Instantly share code, notes, and snippets.

@jsdecena
Created March 14, 2018 13:37
Show Gist options
  • Select an option

  • Save jsdecena/0d33c2bc9d6f83cc1ab0dcfe9d530acc to your computer and use it in GitHub Desktop.

Select an option

Save jsdecena/0d33c2bc9d6f83cc1ab0dcfe9d530acc to your computer and use it in GitHub Desktop.
<?php
namespace App\Http\Controllers\Api\v1;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class PostController extends Controller
{
public function index()
{
$postRepository = new PostRepository(new Post);
$posts = $postRepository->listAllPosts('desc');
$posts->categories = $postRepository->listCategories();
return response()->json([
'data' => $posts,
'status' => 200
], 200)
}
}
//Post Repository
namespace App;
use App\Post;
use Illuminate\Support\Collection;
class PostRepository {
protected $model;
public function __construct(Post $post)
{
$this->model = $post;
}
/**
*
* Return all the posts
* @param string $sort
* @return Collection
*/
public function listAllPosts($sort = 'desc') : Collection
{
return $this->model->orderBy('id', $sort)->get();
}
/**
*
* Return all related categories of the post
* @return Collection
*/
public function listCategories() : Collection
{
return $this->model->categories()->get();
}
}
// Post Model
namespace App;
use App\Category;
use Illuminate\Database\Eloquent\Model;
class Post extends Model {
....
public function categories()
{
return $this->belongsToMany(Category::class);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment