I am trying to do is that if a user is not logged in and trying to enter addPost in the url in addressbar of chrome like www.siteurl/addPost and searching for it then user should redirected to LoginPage.blade.php which is in my views folder. But it throws an error : MethodNotAllowedHttpException No message I tried a lot but unable to find where I am doing wrong. Can anybody help me out. Thank you in advance.
A.This is my view(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.This is my route(web.php) :
Route::group(['middleware' => 'checkuser'], function () {
Route::post('/addPost', 'PostsController@addNewPost');
});
Route::get('/LoginPage', function () {
return view('LoginPage');
});
C.This is addNewPost function in PostsController :
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.This is my custom middleware :
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.Added this to Kernel.php in the $routeMiddleware property array:
'checkuser' => \App\Http\Middleware\CheckUser::class,
Add this line in your web.php
Route::group(['middleware' => 'checkuser'], function () {
Route::get('/addPost', 'PostsController@createPost');
Route::post('/addPost', 'PostsController@addNewPost');
});
This method in your controller
public function createPost()
{
// this is method to show your Addpost.blade.php file
return view('Addpost');
}
And don't forget to add this inside your <form>
tag
{{ csrf_field() }}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.