当我使用laravel中间件时,其路由无法正常工作
<?php
namespace App\Http\Controllers;
use Auth;
use App\Article;
use App\Http\Requests;
use Illuminate\Http\Request;
use App\Http\Requests\ArticleRequest;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
//use Illuminate\Http\Request;
class ArticlesController extends Controller
{
public function __construct(){
$this->middleware('auth',['only'=>'create']);
}
//
public function index(){
//return \Auth::user();
$articles = Article::latest('published_at')->published()->get();
return view('articles.index',compact('articles'));
}
public function show($id){
$article = Article::findorFail($id);
//dd($article->published_at->addDays(8)->diffForHumans());
return view('articles.show',compact('article'));
}
public function create(){
if(Auth::guest()){
return redirect('articles');
}
return view('articles.create');
}
public function store(ArticleRequest $request){
/*
$input = Request::all();
$input['published_at'] = Carbon::now();
*/
$article = new Article($request->all());
Auth::user()->articles()->save($article);
//Article::create($request->all());
return redirect('articles');
}
public function edit($id){
$article = Article::findorFail($id);
return view('articles.edit', compact('article'));
}
public function update($id, ArticleRequest $request){
$article = Article::findorFail($id);
$article->update($request->all());
return redirect('articles');
}
}
当我去http://localhost/lernlaravel/public/articles/create时它工作正常 但当我转到http://localhost/learnlaravel/public/articles时,它会重定向到http://localhost/articles。
index()方法用于列出文章如何修复它?
答案 0 :(得分:1)
redirect ()
接受网址路径,因此如果您希望确保重定向适用于测试环境和生产环境,我会将action ()
或route ()
传递给您的所有应用程序重定向调用。在这种情况下,我会选择
return redirect(action ('ArticlesController@show', $articles->id));
这样,Laravel将自动为您想要处理请求的控制器生成正确的URL路径。
如果您选择使用route()
,您需要在路线文件中命名路线,但我发现使用资源丰富的控制器时,采取行动并不复杂。