Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.