Laravel routes for admin and users - laravel

i have 2 logins pages on my project
1) cms/admin/login
2) cms/users/login
How to redirect if user to user login page
cms/users/login
and if admin call
cms/admin/ redirect to cms/admin/login page

First of all, you don't know if user is user or admin until he logs into your app, so having 2 different routes for same thing is kinda bad. To achieve something similar what you want, you will need to have one cms/login route where user/admin will login and depending on his status (e.g. 1 - user, 2 - admin) you redirect him on cms/user/page or cms/admin/page. To make this you will have to use Middleware which is very good documented in Laravel official documentation.
For example your middleware for all admin pages should look like this
<?php
namespace App\Http\Middleware;
use Closure;
class AdminMiddleware
{
/**
* Run the request filter.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if ($request->input('status') == 2) {
//2 means its admin and i let him get that admin page
return $next($request);
}
//he is not admin so i redirect him back
return Redirect::back();
}
}
In Kernel.php you add middleware alias
protected $routeMiddleware = [
'admin' => \App\Http\Middleware\AdminMiddleware::class,
];
And in routes.php you assign middleware to that routes
Route::get('/cms/admin/page', ['middleware' => 'admin', 'uses'=>'Controller#method']);
Hope it helps

Related

Redirect to intended url after visiting many page in Laravel

I want my website visitors' to redirect to the intended url after login. Suppose, I've a protected page dashboard. If any guest tries to access to dashboard, he get redirected to login page. Now, Instead of login he visited other pages and then returned to login page intentionally. How can I redirect him to the previously intended dashboard page after this login?
It would depend on how you're handling the login action, for example if using the RedirectIfAuthenticated middleware you can make the following change:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
/**
* 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)->check()) {
// return redirect('/home');
return redirect()->intended('dashboard');
}
return $next($request);
}
}
This will redirect the user to whatever page they intended on accessing and send them to /dashboard by default. You could further extend this by using a different fallback URL depending on the users role in case guests or administrators need to land at a different page after login.

Laravel - limiting users for number of posts

Is there any way to limit users in my project for number of posts. For example, I want my users can create a maximum 10 posts each one. So one user has 10 posts? Is it something with hasMany or something else? Please help find a solution. Thank you
By definition
Middleware provide a convenient mechanism for filtering HTTP requests
entering your application. For example, Laravel includes a middleware
that verifies the user of your application is authenticated. If the
user is not authenticated, the middleware will redirect the user to
the login screen. However, if the user is authenticated, the
middleware will allow the request to proceed further into the
application.
To prevent user from adding more than 10 posts you need to create a middleware to protect your posts/create route
To create a new middleware, use the make:middleware Artisan command:
php artisan make:middleware CheckUserPostsNumber
This command will place a new CheckUserPostsNumber class within your app/Http/Middleware directory. In this middleware, we will only allow access to the posts/create route if the user posts number < than 10. Otherwise, you will redirect the user back to the home URI:
<?php
namespace App\Http\Middleware;
use Illuminate\Support\Facades\Auth;
use Closure;
class CheckUserPostsNumber
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (Auth::user()->posts->count() >= 10) {
return redirect('home');
}
return $next($request);
}
}
Assigning Middleware To Routes
you would like to assign middleware to specific routes, you should first assign the middleware a key in your app/Http/Kernel.php file. By default, the $routeMiddleware property of this class contains entries for the middleware included with Laravel. To add your own, append it to this list and assign it a key of your choosing:
// Within App\Http\Kernel Class...
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
//...
'checkUserPostsNumber' => 'App\Http\Middleware\checkUserPostsNumber'
];
Once the middleware has been defined in the HTTP kernel, you may use the middleware method to assign middleware to a route:
Route::get('posts/create', function () {
//
})->middleware('auth', 'checkUserPostsNumber');
Docs
if ($user->posts->count() >= 10) {
//
}

Auth and user management in laravel rest api

I'm writing a rest API for a mobile app. I don't know how to auth users and admins in my app.
I have a table named "users" and have a field called "isAdmin" that is 0 or 1.
now when admin sends posts, users can see posts.how do you recommend auth for both of these?
thank you
I recommend you read the documentation about authentication on laravel: https://laravel.com/docs/5.5/authentication
What you have to setup is the following:
Middleware (what routes can the user use and what routes can the admin use)
Edit your model with an isAdmin() function to determine if an user is user or admin
Example of a AdminMiddleware file - create by command line: php artisan make:middleware AdminMiddleware
<?php
namespace App\Http\Middleware;
use Closure;
use Auth;
class AdminMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if(Auth::check() && Auth::user()->isAdmin()){
return $next($request);
}
else{
return view('your_view')->withErrors('You are not logged in');
}
}
}
Example of an User Model isAdmin function - create by command line: php artisan make:model User
public function isAdmin(){
if($this->isAdmin == 1){
return true;
} else {
return false;
}
}
Example of your route file
// #TODO: Set routes for user and admin here...
Route::group(['middleware' => ['admin']], function () {
// #TODO: Set admin routes here, only admin can use this routes.
});
You also have to edit your Kernel.php a bit:
protected $routeMiddleware = [
// ... add this line
'admin' => \App\Http\Middleware\AdminMiddleware::class,
];

Looking for some helps in adding policy to my laravel projects

I am new in learning laravel. Currently I have been stuck in the Laravel Policy,could you please kindly help with directing me how to add policy to my project?
I would like to make just only the Administrator User be able to see the 'Administration Dashboard' by using Laravel Policies Rules but failed. Actually every registered user is able to see that entrance(just like the attached picture showing below).
The user name is uu#gmail.com and the password is uuuuuu.
Please go to my testing website http://lookoko.com/ and log with the user name and password you will see that Administration Dashboard list in the drop-down lists.
To create a new middleware, use the make:middleware Artisan command:
php artisan make:middleware AdminMiddleware
This command will place a new AdminMiddleware class within your app/Http/Middleware directory. In this middleware, we will only allow access to the route if the logged-in user is admin. Otherwise, we will redirect the users back to the home URI.
<?php
namespace App\Http\Middleware;
use Closure;
class AdminMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (! auth()->user()->is_admin) {
return redirect()->route('home');
}
return $next($request);
}
}
Here I am assumming you have a column in user table named is_admin
Registering Middleware
You should assign the middleware a key in your app/Http/Kernel.php file. By default, the $routeMiddleware property of this class contains entries for the middleware included with Laravel. To add your own, simply append it to this list and assign it a key of your choosing. For example:
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
...
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'admin' => \App\Http\Middleware\AdminMiddleware::class,
];
Once the middleware has been defined in the HTTP kernel, you may use the group method to assign middleware to group of routes:
Route::group(['middleware' => ['admin']], function () {
// all your admin routes comes here
});
Docs

What is use of middleware in Laravel?

I'm not clear with the concept of middleware in Laravel. What does laravel middleware do? Please provide an example if possible.
Middleware is something that is placed between two requests.
Suppose that you need to make sure that when user access to a specific group of routes he/she is authenticated.
There are two option:
Add in every controller the code to check if user is logged in ( in this example we do not consider a parent controller )
Use a middleware
In the first case you should write in each controller the same code.
With the middleware you have a piece of code that you can re-use in multiple section of your application.
Let's suppose that we want to create a Middleware that need to check if the user is logged in:
namespace App\Http\Middleware;
use Closure;
class UserIsLoggedIn
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (!auth()->user()) {
return redirect('home');
}
return $next($request);
}
}
Now with this code we can check our user where we need.
First of all since this is a custom middleware you need to register it in the app/Http/Kernel.php file in the $routeMiddleware property:
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
// ...
'isLoggedIn => \App\Http\Middleware\UserIsLoggedIn::class,
];
Let's assume that you have a group of routes that need to check the user is logged in:
Route::get('admin/profile', function () {
//
})->middleware('isLoggedIn');
Now all the routes in this group will check if the user is logged otherwise he will be redirect to home.
Now assume that you have another controller that need to make sure that the user is logged in, now you can re-use the middleware to do that:
class MyController extend Controller {
function __construct(){
$this->middleware('isLoggedIn');
}
}
So middleware help you to organize the login and re-use pieces of code for specific tasks.
Laravel has a lot of documentation about middleware that you can find here

Resources