我想要做的是,如果用户没有登录并尝试在Chrome地址栏中的URL中输入addPost,如www.siteurl / addPost并搜索它,那么用户应该重定向到LoginPage.blade.php在我的视图文件夹中。但它抛出错误: MethodNotAllowedHttpException 没有消息 我尝试了很多,但无法找到我做错的地方。任何人都可以帮助我。先感谢您。
A.这是我的视图(Addpost.blde.php):
<form action="{{URL::to('/addPost')}}" method="post">
<input type="text" name="post_title" id="post_title" />
<textarea name="post_description" id="post_description" ></textarea>
<button type="submit" name="post">Post</button>
</form>
B.这是我的路线(web.php):
Route::group(['middleware' => 'checkuser'], function () {
Route::post('/addPost', 'PostsController@addNewPost');
});
Route::get('/LoginPage', function () {
return view('LoginPage');
});
C.这是PostsController中的 addNewPost函数:
public function addNewPost(Request $request){
$userid = Session::get('id');
$post_title = $request->input('post_title');
$post_description = $request->input('post_description');
$addPostintoDB = new MyPostsModel(['user_id' => $userid, 'post_title'=> $post_title, 'post_description'=> $post_description]);
$addPostintoDB->save();
echo "post saved";
}
D.这是我的自定义中间件:
namespace App\Http\Middleware;
use Closure;
use Session;
class CheckUser
{
public function handle($request, Closure $next)
{
if (!Session::get('id')) {
return redirect('/LoginPage');
}
return $next($request);
}
}
E.将此添加到$ routeMiddleware属性数组中的 Kernel.php :
'checkuser' => \App\Http\Middleware\CheckUser::class,
答案 0 :(得分:0)
在web.php中添加此行
Route::group(['middleware' => 'checkuser'], function () {
Route::get('/addPost', 'PostsController@createPost');
Route::post('/addPost', 'PostsController@addNewPost');
});
控制器中的此方法
public function createPost()
{
// this is method to show your Addpost.blade.php file
return view('Addpost');
}
不要忘记在<form>
标记
{{ csrf_field() }}