我不知道如果laravel可以做到这一点或者实现它的最佳方式是什么,我想,如果用户点击发布或添加到收藏夹并且他没有通过身份验证登录表格,
我希望每个访问者都可以访问所有帖子,我在if(auth::check())
之前使用过我的视图来隐藏或显示按钮(如&收藏),如果用户通过身份验证,但我不喜欢这条路。我想向所有访问者显示按钮,但是当未经身份验证的用户单击按钮重定向到登录页面时。
我试图将此方法添加到我的路线,但似乎无法正常工作
if (Auth:check()){
Route::post('/favorite/{post}', 'SiteController@favorite');
Route::post('/unfavorite/{post}', 'SiteController@unFavorite');
Route::post('/like/{post}', 'SiteController@like');
Route::post('/update/{post}', 'SiteController@update');
Route::post('/unlike/{post}', 'SiteController@unLike');
} else {
Route::get('/login', ['as' => 'login', 'uses' => 'Auth\LoginController@showLoginForm']);
答案 0 :(得分:2)
你应该使用middlewares来做这样的事情。将您希望仅登录用户的路由分组以访问并使用该路由上的中间件来检查用户是否已通过身份验证。
实施例:
web.php
<?php
// Routes for logged in users.
$router->group(['middleware' => ['auth']], function($router) {
$router->get('foobar', ['as' => 'foobar', 'uses' => 'FooController@index']);
});
// Routes for all users.
$router->get('bar', ['as' => 'bar', 'uses' => 'BarController@index']);
App\Http\Middleware\Authenticate.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class Authenticate
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest(route('bar'));
}
}
view()->share('user', Auth::user());
return $next($request);
}
}
然后在App\Http\Kernel.php
中将此内容添加到$routeMiddleware
数组中:
'auth' => \App\Http\Middleware\Authenticate::class,
答案 1 :(得分:1)
要使相似按钮可见,您必须删除视图中的auth::check())
并将其添加到web.php
:
// Routes for guest users
// Add here the route for your posts
// Routes for logged-in users
Route::group(['middleware' => ['auth']], function () {
Route::post('/favorite/{post}', 'SiteController@favorite');
Route::post('/unfavorite/{post}', 'SiteController@unFavorite');
Route::post('/like/{post}', 'SiteController@like');
Route::post('/update/{post}', 'SiteController@update');
Route::post('/unlike/{post}', 'SiteController@unLike');
}