Created
January 3, 2017 16:41
-
-
Save martinbean/fde974ad1755f075abaf25862be120c4 to your computer and use it in GitHub Desktop.
Request-driven development
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\News; | |
use Illuminate\Database\Eloquent\Model; | |
class Article extends Model | |
{ | |
public function publish() | |
{ | |
return $this->forceFill([ | |
'published_at' => $this->freshTimestamp(), | |
])->save(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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')); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 anApp\News\Article
instance. The corresponding route would look something like this: