Auth::check always return null - php

I'm trying to make a button appear when a user log in. If the user isn't log in, the button wouldn't appear on the page. So the first thing i need is to determine if the user has log in or not. The problem is, The Auth::check() keeps returning null. I've done research that we should put the route inside the Auth middleware, but in doing so, users would have to log in to see the page and i don't want that. I want the users to be able to see the page without login and when they do login, a button will appear on the same page.
Component
<button v-if="showBtnDelete==true" class="btn btn-danger">Delete</button>
<script>
getUserType(){
axios.get('api/gallery/getUserType').then(res=>{
this.showBtnDelete = res.data;});
},
</script>
Controller
public function getUserType()
{
if(Auth::check()){
return 'true';
}else{
return 'false';
}
}
Web.php
Route::group(['middleware' => ['auth']],function(){
Route::get('/add-image', function () {return view('layouts.master');});
});
Auth::routes();
Route::get('/logout','Auth\LoginController#logout');
Route::get('/', function () {
return view('home');
});
Route::get('{path?}', function () {
return view('layouts.master');
})->where('path', '[\/\w\.-]*');

guard API or web
Auth::guard('api')->check();
Auth::guard('web')->check()

You're returning 'true' and 'false' as strings which both returns true when non strictly compared and false when strictly compared
echo 'false' == true; // true
echo 'false' === true; // false (not same data type)
And vice versa...
Now Auth::check() naturally returns a boolean so the if, else statement is redundant all together...
You can use the helper method to use each guard when needed
public function getUserType()
{
return auth()->check();
}

If anyone has the same problem. The problem is that your route is not protected by the middleware group web.
That means it will not be able to retrieve the session of the current user so the Auth facade will always return null.
Add middleware('web') to the route accessing the method (code) and you will be able to retrieve the current user if logged in.

Related

Laravel route when where condition is false

I have the next code:
Route::get('/{lang}/user/sort-by-{class}', function ($lang,$class) {
return view('users.list',compact("lang","class"));
})->where('class', '[a-z]+');
Route::get('/{lang}/user/{user}', function ($lang,$user) {
return view('users.user',compact("lang","user"));
});
When condition in where is false, how can I send it directly to 404 when sort-by- is for example a number? The problem is that it goes to secondary route as an user.
For example:
/en/user/sort-by-name is ok
/en/user/sort-by-4446 must show 404 page
I know that i can do another route just between them with
Route::get('/{lang}/user/sort-by-{class}', function ($lang,$class) {
return \Response::view('errors.404',array(),404);
})->where('class', '.*');
but this seems ugly, i would like in same sentence
Basically, you may do this
Route::get('/{lang}/user/sort-by-{class}', function ($lang,$class) {
if (is_numeric($class)) {
abort(404, 'Your reason');
}
return view('heros.list',compact("lang","class"));
});
Though, using closures in routes is a bad practice because they cannot be serialized in production mode. That's why you should use a controller to return your view, and assign a middleware to this route which will check your class and abort the request if needed.

Preserve url parameters if user is not authenticated on specific page (Laravel)

I'm passing these params from firstsite.com
param1 = value
param2 = value
to
secondsite.com
Like this
http://secondsite.com/pay?param1=value&param2=value
But the pay.blade.php is under of middleware
where pay.blade.php accessible only for authenticated users.
and I want to redirect them to http://secondsite.com/login?param1=value&param2=value
where params is still exists.
But in my case the params of course disappears and redirect to login.blade.php since it is stated on my web.php routes.
Here's my route
Route::group(['middleware'=> ['auth']], function(){
Route::get('/pay', 'PayController#index');
});
PayController.php
public function index()
{
if(session()->get('merchId') == "")
{
abort(404);
}
else
{
return view('pay');
}
}
But as of now I'm declaring abort(404) and will revise it once I'm done with my objective
Is it possible to keep those params going to login.blade.php?

Add Admin role in laravel 5.4

I have a database that in this: Admin has True isAdmin property, but other users have false isAdmin property.
I want to check if the user who logged in is an Admin or not by redirecting them to different pages in my app. My code in Controller is:
public function store(User $user)
{
if (auth()->attempt(request(['email', 'password']))) {
if ($user->isAdmin == 1) {
return redirect('/ShowUser');
}
{
return redirect('/lo');
}
}
return back()->withErrors(
[
'message' => 'Error'
]
);
}
But this code doesn't work; it sends the users to '/lo' all the time. How can I fix it?
You're missing an else keyword.
Right here:
if ($user->isAdmin == 1) {
return redirect('/ShowUser');
}
{ // <-- right here
return redirect('/lo');
}
add the else keyword.
if ($user->isAdmin == 1) {
return redirect('/ShowUser');
}
else { // <-- right here
return redirect('/lo');
}
anyway, your code will still run fine even after the edit above. But I have questions for you:
Is the user assumed to be in the database already?
What is the default value of isAdmin in the database?
Are you passing the isAdmin attribute as an input from a form or something?
And why is it a store request when you're just trying to log a user in?
It's a bit confusing. I can tell from your code that you're trying to log a user in, but you're doing it in a store method (nothing wrong with that, just convention), the store method is usually used in storing data (how coincidental!)

How to determine if a session with same variable is already there in laravel

I am using Laravel framework. There is a function in controller that creates session with name store_id
StoreController.php
function initiate($id)
{
//Some queries
session['store_id' => 'some value'];
}
Now if I run this function on one tab then session::get('store_id') is going on. But if I open another tab in the same browser then again run the function that means session('store_id') will be again set. How do I handle this situation that if there is already a session then it should redirect to it's perspective url.
Okay first of all, Bruuuhhhh been there and done that
Alright, lets begin. you want that if there is already a session with store_id going on then you want user to redirect or send back.
In your controller add this
public function initiate()
{
if(session()->has('store_id'))
{
//What ever your logic
}
else
{
redirect()->to('/store')->withErrors(['check' => "You have session activated for here!."]);
}
}
Most probably you would be wondering that user can just go to other url after /store/other-urls Yess he can.
To avoid this. Add a custom middleware
php artisan make:middleware SessionOfStore //You can name it anything.
In that middleware
public function handle($request, Closure $next)
{
if($request->session()->has('store_id'))
{
return $next($request);
}
else
{
return redirect()->back()->withErrors(['privilege_check' => "You are not privileged to go there!."]);
}
return '/home';
}
in your main store page. Add an anchor tag Stop Service
Now in your web.php
Route::group(['middleware' => 'SessionOfStore'], function()
{
//Add your routes here.
Route::get('/stop', 'StoreController#flushSession');
});
Now you have restrict access to urls and has checked the sessions.
Now in
public function flushSession()
{
//empty out the session and
return redirect()->to('/home');
}
The Laravel session helper has the function has to check this.
if (session()->has('store_id'))
{
// Redirect to the store
}
else
{
// Set the store id
}
The documentation contains all of the possible functions that can be used with the session helper.

Laravel 4 routing to controller method

I'm currently trying to route as follows:
If user GETs /account/
If session has account_id, user is logged in; show his account information
If not, user is not logged in; show login/create form
If user POSTs /account/
If input has create, user wants to create account; create it
If not, user wants to login; find his account and go again to /account/
My routes are set this way:
Route::get('account', function() {
if (Session::has('account_id'))
return 'AccountsController#show';
else
return 'AccountsController#index';
});
Route::post('account', function() {
if (Input::has('create')) {
return 'AccountsController#create';
else
return 'AccountsController#login';
)};
This is somewhat how I would do with Rails, but I don't know how to point to the controller method. I just get the returned string as a result. I didn't find it in Laravel documentation (which I found really poor, or have I searched wrong?) neither in any other web tutorial.
Try the following:
Route::get('account', function() {
if (Session::has('account_id')) {
$action = 'show';
return App::make('AccountsController')->$action();
}
else {
$action = 'index';
return App::make('AccountsController')->$action();
}
});
Route::post('account', function() {
if (Input::has('create')) {
$action = 'create';
return App::make('AccountsController')->$action();
}
else {
$action = 'login';
return App::make('AccountsController')->$action();
}
)};
So, you want to put all your logic in the controllers.
You would want to do
Route::get('account', 'AccountsController#someFunction');
Route::get('account', 'AccountsController#anotherFunction');
Then, in the respective controllers, you would want to make your tests, then do, for example,
if (Session::has('account_id')){
return Redirect::action('AccountsController#show');
}
else{
return Redirect::action('AccountsController#index');
}
However, make sure you define a route for each action, so your application can detect a URL.
For example, if you want to have
Redirect::action('AccountsController#show')
you will need to define this action like:
Route::get('/account/show', 'AccountsController#show')

Categories