Reputation: 120
I don't know If this is possible with laravel or what is the best way to achieve it, i wan't if user click to like post or add to favorites and he is not authenticated to showing login form,
I want every visitor to have access to all posts, i have used before if(auth::check())
in my view to hide or display the buttons (like & favorite) if user authenticated, but i don't like this way. i want to display the buttons to all visitors but when a Unauthenticated user click on like button redirecting to login page.
I tried to add this method to my routes but seems not working
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']);
Upvotes: 0
Views: 7219
Reputation: 3912
To make the like button visible you have to remove the auth::check())
in your views and add this to your 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');
}
Upvotes: 1
Reputation: 29413
You are supposed to use middlewares for things like this. Group the routes you want only logged in users to have access to and use a middleware on that route to check if the user is authenticated.
Example:
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);
}
}
Then in App\Http\Kernel.php
you add this to your $routeMiddleware
array:
'auth' => \App\Http\Middleware\Authenticate::class,
Upvotes: 3