Skip to content

Instantly share code, notes, and snippets.

@martinbean
Created January 3, 2017 16:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martinbean/fde974ad1755f075abaf25862be120c4 to your computer and use it in GitHub Desktop.
Save martinbean/fde974ad1755f075abaf25862be120c4 to your computer and use it in GitHub Desktop.
Request-driven development
<?php
namespace App\News;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
public function publish()
{
return $this->forceFill([
'published_at' => $this->freshTimestamp(),
])->save();
}
}
<?php
namespace App\Http\Controllers\News;
use App\Http\Controllers\Controller;
use App\Http\Requests\PublishArticleRequest;
use App\News\Article;
class ArticleController extends Controller
{
public function publish(PublishArticleRequest $request, Article $article)
{
$request->handle();
return redirect()
->route('article.show', $article)
->withSuccess(trans('messages.article_published'));
}
}
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class PublishArticleRequest extends FormRequest
{
public function authorize()
{
return $this->user()->can('publish', $this->article);
}
public function rules()
{
return [];
}
public function handle()
{
return $this->article->publish();
}
}
@martinbean
Copy link
Author

martinbean commented Jan 3, 2017

Example showing form request classes being used by controllers to perform the action it intends in a Laravel 5.x application.

So long as route–model binding is used, $this->article in the request class would be an App\News\Article instance. The corresponding route would look something like this:

Route::post('articles/{article}/publish', 'News\ArticleController@publish');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment