Skip to content

Instantly share code, notes, and snippets.

@martinbean
Created March 26, 2018 13:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martinbean/453ac1dbedeebdf2da71e0fe13fd4ac6 to your computer and use it in GitHub Desktop.
Save martinbean/453ac1dbedeebdf2da71e0fe13fd4ac6 to your computer and use it in GitHub Desktop.
Using Laravel’s Responsable interface to create view models
<?php
namespace App\Http\Controllers;
use App\Article;
use App\Http\Views\ArticleIndex;
class ArticleController extends Controller
{
public function index()
{
$articles = Article::latest()->paginate();
return new ArticleIndex($articles);
}
}
<?php
namespace App\Http\Views;
use App\Http\Resources\ArticleResource;
use Illuminate\Contracts\Support\Responsable;
use Illuminate\Database\Eloquent\Collection;
class ArticleIndex implements Responsable
{
private $articles;
public function __construct(Collection $articles)
{
$this->articles = $articles;
}
public function toResponse($request)
{
if ($request->wantsJson()) {
return ArticleResource::collection($articles);
} elseif ($request->wantsRss()) {
return view('article.rss', compact('articles'));
} else {
return view('article.index', compact('articles'));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment