larafever

larafever

Mobile Applications Developer at PaySwitch Ghana

Member Since 3 Years Ago

Accra

Experience Points
12,960
Total
Experience

2,040 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
88
Lessons
Completed
Best Reply Awards
5
Best Reply
Awards
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

Level 3
12,960 XP
May
28
4 months ago
Activity icon

Replied to Password Reset Link, Incorrect Format And Invalid Token - Laravel 5.7 Multi Language

Route::post('/password/reset', 'Auth\[email protected]')->name('password.reset');

this needs to be refactored to

php
Route::post('/password/reset/{token}', 'Auth\[email protected]')->name('password.reset');

using this way, I presume that password.reset route is in a route group that enforce locale prefixing

php

Route::group(["prefix"=>"en"],function(){

//sub routes here

});
Activity icon

Replied to I Want If User Register Successfully Then User Will Come Next Time The Registration Will Not Be Show For That User.

If you are implementing the default authentication flow then you can use the guest middleware on the registration route

php

Route::get('/register')->middleware('guest');

or add it in the construct method of the class which has the registration method

May
27
4 months ago
Activity icon

Replied to Redirect To Other Server After Login

Are you trying redirect to an external url?

return redirect()->away('domain.com');

Activity icon

Replied to Eloquent Relationship 1 To 1: With() Not Working

Since both tables have column id and id in permission groups table is referenced in permissions table, calling the with method with limited related column should always include the referential column in this case ID in permission groups table

Activity icon

Replied to Eloquent Relationship 1 To 1: With() Not Working

@SNAPEY - I think it should be

$permission = Permission::with('permission_group:id,name')->get();

instead

Jul
02
2 years ago
Mar
26
2 years ago
Activity icon

Replied to Display Image

First run the artisan command ~php artisan storage:link

This command is going to create a shortcut of ..\storage\app\public folder in the public folder in your root directory.

Now if you are using Laravel's default filesystem driver which is local then you can serve your image using

<img src="{{(url('/storage/uploads',$user->image))}"/>

if file name may contain any url unfriendly characters then use the

<img src="{{ urldecode(url('/storage/uploads',$user->image))}"/>

MAKE SURE THE UPLOADS FOLDER RESIDES IN THE LARAVEL STORAGE\APP\PUBLIC\ FOLDER

I think it will work if your path is set right

Activity icon

Replied to Display Image

Try this

<img src="{{ urldecode(url('/storage/uploads',$user->image))}"/>

I think it will work if your path is set right

Mar
23
2 years ago
Activity icon

Replied to I Have Issue In Laravel Random() Query .

Try


$data = User::where('id','!=',5)->inRandomOrder()->take(10)->get();

Mar
21
2 years ago
Activity icon

Replied to Count Voting Results

Go the model way pal

Activity icon

Replied to Redirect Does Not Work After Login

Try this in the LoginController


private authenticated($request,$user){
return redirect('/admin');
}
Feb
09
2 years ago
Activity icon

Replied to Authentication Problem In 5.3

Authenticated user can't called in the __construct() , besides laravel auto check if authenticated already or redirect to login automatically once you add the

public __construct(){
$this->middleware('auth');
}
Activity icon

Replied to Authentication Problem In 5.3

Authenticated user can't called in the __construct() , besides laravel auto check if authenticated already or redirect to login automatically once you add the ```php public __construct(){ $this->middleware('auth'); }

Activity icon

Replied to Authentication Problem In 5.3

if you are using the default login controller that uses Illuminate\Foundation\Auth\AuthenticatesUsers then you can use the authenticated method to get the authenticated user where you can assign it to a variable


  protected function authenticated(Request $request, $user){
      $this->user = $user;
    }

Feb
07
2 years ago
Activity icon

Replied to Eagear Loading Multiple Tables

Try this

$this->menus = UserProfile::with(['permissions' => function ($q) {
      $q->select('id', 'page_name', 'page', 'view', 'submit', 'print', 'user_profiles_id')->first();
   }])->get();
Activity icon

Replied to Error 500 (Internal Server Error) In Ajax Request

you forgot CSRF-TOKEN field for your ajax request

Activity icon

Replied to Problem With Eloquent Relations In My Project

try this, your codes are long for digestion,

$tasklist = TaskDetails::with(['type','userList'])->get();

Activity icon

Replied to Eagear Loading Multiple Tables

try this is more eloquent approach

class Permission extends Model
{
    public function user_profiles()
    {
      return $this->belongsTo('App\UserProfile','user_profiles_id');
// just add second param and this will reference a foreign key column that connects the permissions model and the users profile
    }
}

user

class User extends Model
{
    public function user_profiles()
    {
        return $this->hasOne('App\UserProfile','user_profiles_id','id');
//the relationship should be user has one userprofile using the fk column user_id in the userprofile table and id in the user table
    }
}

userprofile

class UserProfile extends Model
{
    public function users()
    {
        return $this->belongsTo('App\User','user_id');
//relationship is userprofile belongsTo one user, profile cannot be possessed by multiple users
    }

    public function permissions()
    {
      return $this->hasMany('App\Permission','user_profiles_id','id');
    }
}

I don't really know how you want to implement the permissions on users, if users are assign to multiple permission then the above will work fine.

Now eager load

$this->menus = User::select('id', 'username')->with('user_profiles.permissions')->get();

We don't need to do more join join since we have our eloquent relationships but not that all but not $hidden`` columns in bothuser_profilesmodel andpermission``` model will be fetched.. We can hide columns that are irrelevant to most of our queries by using the

class UserProfile extends model{

    protected $hidden = ['your_columns_that_are_irrelevant'];
}

Hope it helps

Activity icon

Replied to Local Install On Windows

I have been using xampp for a while, currently running php 7.0.13, it is helpful if you are running multiple projects using different frameworks, I start my server on startup and all you need is localhost/path_to_project, and it's even fun with the vhost config where you can have virtual address for every project.. Mamp on windows sucks, 30 days trial and you get stranded

Activity icon

Replied to Laravel Login Encrypt And Bcrypt Method?

For registration use

bcrypt($your_password)// encrypt password for users

Then use

Auth::attempt(['username'=>$username,'password'=>$password]);
//Laravel automatically Hash check password for logins if you use the Auth::attempt(), and make sure your password column in your db is named password else this will not work
Feb
06
2 years ago
Activity icon

Replied to Laravel Job

Can't you eager load in the constructor ?


protected $message;

public __constructor(Message::class $message){
$this->message = $message->load(['forum','user']);
}

I think this should work if you inject the Message class as a dependency for that job

Feb
05
2 years ago
Activity icon

Replied to How To Reference Item In Multi-dimensional Array/collection

Too many codes to digest pal, but i hope you got the out put below, as show above in your explanation...

I think you have to do one more foreach loop in the items, since is array from your explanation

Activity icon

Replied to Do I Really Need Server Side Validation?

Server side validation should be your last data transfer check ( incoming and outgoing ), you can do checks on request type (ajax and non-ajax ) and act accordingly but make sure there is an ultimate fallback especially for ajax request

Jan
20
2 years ago
Activity icon

Replied to Secure Register Form From Preventing Html Injection

@mbpp then user being changed type to 2 will be validated as 2 type and validation will be true if 2 exists as a TYPE ID... I think your registration process for both users have a distinct difference in inputs and some similarities, if so then can break your validation down to specific validation rule for specific type ID then use what I illustrated earlier as general validation...

Activity icon

Replied to Question About Eloquent Model

Can you explain further...?

Activity icon

Replied to Secure Register Form From Preventing Html Injection

Why don't use the L5.3 validator ... I'm using the same two way user registration method on one controller ...

Just validate the hidden account type, create one model for the account types then do eloquent model relationship like user belongsTo account type model and account type model hasMany users..

In the migration for account types

Id->increments Title->unique

Then in your users table just do

Type_id->integer|unsigned|index Then create FK on type_I'd

So when you validating the form

account_type => 'required|digits:1|exists:account_types,id

Use digits to accept only numbers and 1 for string length, so let say 1 or 2 or 3 ... 9 not two digit number. Then the number should exist in account types table under ID column

Jan
19
2 years ago
Activity icon

Replied to Authentication Error

sorry for the formatting I'm having problems with my browser tho

Hope it helps

Activity icon

Replied to Authentication Error

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest', ['except' => 'logout']);
    }
    
    /**
     * Show the application's login form.
     *
     * @return \Illuminate\Http\Response
     */
    public function showLoginForm(){
        return view('auth.login.login');
//return your login view
    }
    
     protected function username(){
        return "username";
//return the column specified as username, the default is email, I used username
    }
    
    protected function validateLogin(Request $request)
    {
        $this->validate($request, [
            $this->username() => 'required|min:6|alpha_dash', 'password' => 'required|min:8',
        ]);

//Validate  the login form, make sure your form inputs has names attributes as specified here, so username input named username should be the same as the keys for validation

Activity icon

Replied to Authentication Error

We can do this without copying all the AuthenticatesUsers trait

Try this and I think you will be fine with the controller


<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
%
Jan
18
2 years ago
Activity icon

Replied to How To Remove An Item From A List With Given ID In VueJS

ooh ok... sorry I'm not into FrontEnd tho

Activity icon

Replied to How To Save Multiple Query Results In One Array?

Sorry for the late reply I was away for work..

let solve the issue of latest post...


//here we want the 5 latest in each category

$eachCategoryWith5 = Category::all()->map(function ($category, $key){
    return $category->posts->latest()->take(5);
    });

//just use the latest method if you have created_at column in your post table

//if you don't have a created_at column in your table we can use the id of the post since it increments for each post we add, just fetch from below to top take the first 5 post

$eachCategoryWith5 = Category::all()->map(function ($category, $key){
    return $category->posts->order('id','desc')->take(5);
    });

okay let's start with Category::all() this fetch all the categories we have, ->map() is a helper method in that enables you to do iterations on collections. Note that in L5.3 all eloquent models return Collections therefore we can call collections helper methods on them learn more at https://laravel.com/docs/5.3/collections. function($category, $key) is the same as function($item, $key) Since we are iterating on the collection Category::all() we need to get each (in this case let say category in categories) item in the collection. That item at the current iterate is $category or $item and that should be the first parameter in the inner function() the $key is current index of the iterate..

Let's do this quick illustration


//LETS SAY Category::all() return the collection and assigned to $cat below

$cat = {[
        {
            id:1,
            name:"Music"
            created_at:"2017-01-17 19:43:47"
            updated_at:"2017-01-17 19:43:47"
        },
        {
            id:2,
            name:"Health"
            created_at:"2017-01-17 19:43:47"
            updated_at:"2017-01-17 19:43:47"
        },
        {
            id:3,
            name:"Entertainment"
            created_at:"2017-01-17 19:43:47"
            updated_at:"2017-01-17 19:43:47"
        }
    ]};

//then we perform iteration on $cat since we need 5 post for each of this category, we can't use foreach loop straight away since we are working with a  collection, so we use the map() helper method to iterate.

//The map() helper method accepts an anonymous function as a parameter to hold off each iteration process, then return the item of the iteration process and the index of the item.. so in our case we are looking for a category in $cat so I'd pass $category as my item and $key as my index  for the item

 
$cat->map(function($category,$key){

//in here is where we get post for each category then return it, and since we have an eloquent relationship we don't need to do more query logic here

/*
so for the first iterate on $cat

$category = {
            id:1,
            name:"Music"
            created_at:"2017-01-17 19:43:47"
            updated_at:"2017-01-17 19:43:47"
        };

so we get all post with category_id of 1 , as per our relationship

*/

    return $category->posts->latest()->take(5);

//since we are using the map() helper function, L5.3 automatically do the pushing for each iteration and at the end we get all the latest 5 post for each category.

});

Hope it helps

Activity icon

Replied to How To Remove An Item From A List With Given ID In VueJS

Take a look at the DOCS on collection.. You can use the collect method on any array to convert it to collection then use Laravel in built collection methods like slice and pull or where to remove by key...

https://laravel.com/docs/5.3/collections

Activity icon

Replied to Laravel Sending Mail Not Working On Production Server

@mojemoron .. You are welcome, can you mark my answer as the best answer?

Jan
17
2 years ago
Activity icon

Replied to Laravel Live Search

The problem I think is returning $results from the Controller..

Try this

return response()->json(['results'=>$result]);

This way you can get the results array as an object in front-end

So in JS you just call

$.ajax().done(function (response){

var results = response.results; });

Sorry for unable to format code, I'm on mobile device...

Activity icon

Replied to Laravel Sending Mail Not Working On Production Server

In the .env file

MAIL_DRIVER=smtp
MAIL_HOST=mail.pearlstack.com
MAIL_PORT=587
MAIL_USERNAME=your client username
MAIL_PASSWORD=youre client password
MAIL_ENCRYPTION=TLS

You check your mail client config from your cpanel or production server for more on the setup info

Activity icon

Replied to How To Save Multiple Query Results In One Array?

okay I think we can create Eloquent Relationship between category model and the post model using category_id so let say on the category model

 
public function posts(){
return $this->hasMany('App\Post','category_id','id');
}

Now you can use the posts method

use App\Category;

//first senario LOAD 5  posts for each category

//use each or map method to do iterations on collections with two param (current item and key of current item ).In our case I use $category as the current item

$eachCategoryWith5 = Category::all()->map(function ($category, $key){
    return $category->posts->take(5);
    });

//we can do anything with $eachCategoryWith5 variable... I will throw it into a view

return view('categories.summary',compact('eachCategoryWith5'));

Then you do multiple foreach in the view since $eachCategoryWith5 a two dimensional array


   @foreach($eachCategoryWith5  as $categoryPost)
            @foreach($catetgoryPost as $post)
            {{$post}}
            @endforeach
     @endforeach

Note that $post will be a collection and therefore syntax like $post->title is acceptable

Hope it helps

Jan
07
2 years ago
Activity icon

Replied to Redirect After Registration Like Login

@jrdw, I think Laravel do all that trick with events that can be fired or broadcast, what i found in the ..\vendor\laravel\framework\src\Illuminate\Foundation\Auth\RegistersUsers.php



//This the default laravel register method 
public function register(Request $request)
    {
    //validates the register form
        $this->validator($request->all())->validate();
    
    //attach new registered user event which can be fired or broadcast
        event(new Registered($user = $this->create($request->all())));
    
    //this automatically login users and enables Auth guard after registration
         $this->guard()->login($user);
    
    /*

this is helper that enables you to do anything with register user or return to a specific URL. By default laravel only redirect to auth middleware after registration since  $this->guard()->login($user); enables Auth guard therefore if you want to redirect to LOGIN, it will be impossible because LOGIN is a Guest guard

*/
        return $this->registered($request, $user)
            ?: redirect($this->redirectPath());
    }

We can override this method to suit our need and still get what Laravel offers by default without changing anything here.. This is how we do it by overriding Register method in RegisterController.php found at ..\app\Http\Controllers\Auth\RegisterController.php

.

use Illuminate\Http\Request;
use Illuminate\Auth\Events\Registered;



//we define our redirectTo
    protected $redirectTo = '/login';



//create a new method that overrides default register 

    public function register(Request $request)
    {
        $this->validator($request->all())->validate();

        event(new Registered($user = $this->create($request->all())));

       // $this->guard()->login($user);
    //this commented to avoid register user being auto logged in

        return $this->registered($request, $user)
            ?: redirect($this->redirectPath());
    }

//we will maintain the default create method but you can tweak it to suit you needs

    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }

 //we can also play with the registered user object thrown after registration using the registered method because you returned that method or redirectPath method in register method.

protected function registered(Request $request, $user)
    {
        //we can send users account formation email here or anything we want with users even fire that Registered event created earlier

}

Hope it helps

Activity icon

Replied to How To Return Validation Errors As JSON To View

@MrRobot21, can you embed your code for this method


 respondCreated();

I can suggest this looking at your code logic

//I created a new respondCreated Method

public function respondCreated($message)
    {
     //if you to return message to view or ajax process
     return response()->json(['message'=>$message]);
     //Pass message parameter as message  for ajax

     //or anything with message

     
    }

  //add a new lesson to lessons table
    public function store(StoreLessons $request) 
    {
        $validator = Validator::make($data, $rules);
        
        if ($validator->fails()) {
    
    //pass validator errors as errors object for ajax response

          return response()->json(['errors'=>$validator->errors()]);
        }
    
    else{
        Lesson::create($request->all());
    
    // call respondCreated and pass message
        return $this->respondCreated('Lesson created successfully');
    }
    }

Embed your code at line 49 and let's see what's happening

Jan
06
2 years ago
Activity icon

Replied to Base Directory Of My Website Is Accessible And That Is Public. How To Make It Hid From Public?

Try this tweak, create a .htaccess file in your base website folder, paste this in it, it should solve your problem


Options -Indexes
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

Activity icon

Replied to How To Return Validation Errors As JSON To View


  //add a new lesson to lessons table
    public function store(StoreLessons $request) 
    {
        $validator = Validator::make($data, $rules);
        
        if ($validator->fails()) {
    
    //pass validator errors as errors object for ajax response

          return response()->json(['errors'=>$validator->errors()]);
        }
    
    else{
        Lesson::create($request->all());
        return $this->respondCreated('Lesson created successfully');
    }
    }

So on client side you can get errors object by:


//after ajax done

$.ajax().done(function(response){
    //check if response has errors object
    if(response.errors){

    // do what you want with errors, 

    }
});

Hope it helps

Activity icon

Replied to 404 Errors

Go to resource folder

Find views folder check if a subfolder called Errors exist if not create a new one..... This where views for HTTP status codes like 404, 503 and more will be hosted....

Create a new blade file with various error codes as name

Example..

404.blade.php - is a view for 404 page

You can create more Error views Laravel will direct users to those views when those errors occurs.

Read more at https://laravel.com/docs/5.3/errors

Activity icon

Replied to Show Html In Blade Email

Try this

 {!! @html_entity_decode($line) !!}

Or

 {!! $line !!}

If $line is rendered as a string

Activity icon

Replied to Get Password Reset Email From Different Model

@martinbean, it's not working... Nothing is happening...

Looking at the snippet you shared earlier, it means there is a relationship between USER and PROFILE where Profile contains EMAIL Column ... I have done ONE TO ONE Relationship but still is not working

Activity icon

Replied to Get Password Reset Email From Different Model

@martinbean , should I override this method via the USER model or the PASSWORDRESET Controller

Jan
05
2 years ago
Activity icon

Started a new conversation Get Password Reset Email From Different Model

I'm using Laravel 5.3 default password reset route and controller but I want get email address from USERPROFILE model where I saved users email, because I'm not using email for authentication but rather USERNAME therefore there is no column like email in my users model.... Any help on how to tweak this?

Activity icon

Replied to Help, How Do I Remove Public/index.php In Url, Having NotFoundHttpException

@daniel.atienza, What I normally do is divide my project into two folders

1.public_html 2.root

The public html containers all my assets ( JS, CSS, images etc ) and can be accessed using blade helper {{URL::to("public_html//")}}

The root contains all laravel base default files and folders expect the PUBLIC folder... This mean you can run artisan command here so you just open cmd in this folder then you set to go..

Now the PUBLIC folder needs to be eliminated and therefore all files in it has to be moved to the base folder so we get the PUBLIC_HTML, ROOT, and the moved files in the base folder ....

U can delete the public folder since it will be empty now..

Now it's time to direct your index.php file to ROOT folder where your app starts...

Change the AUTOLOAD.PHP path to / ROOT/BOOTSTRAP/AUTOLOAD. PHP

Do the same for APP.PHP

/ROOT/BOOTSTRAP/APP.PHP

Done... We are go to load our app without the public and without torching the .HTACCESS file

Now when hosting we can put our ROOT folder containing our app even away from the public_html folder on live server and drop it from visitors reach so no one can get directe access to the ROOT folder, we just tweak our INDEX.PHP file to point to it safely

Sep
16
3 years ago
Activity icon

Replied to Laravel 5.3 Multi Auth - How Can I Make It Work?

@Hesto i think i have a solution for user/admin auth from different models and views with each login view protection after auth check......................................................

first go the CONFIG->AUTH.PHP and the following code in the GUARDS ARRAY

  'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],

tthen in the PROVIDERS ARRAY in AUTH.PHP add

  'admins' => [
            'driver' => 'eloquent',
            'model' => App\Admin::class,
        ]

** note: the model can be changed to table then you specify you table name in the db or you can still use the model then specify your model for your admin

then in your ADMIN model use this

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class Admin extends Authenticatable
{

}

you have to create a middleware for your admin pages/routes you can use this to protect your login page and after login pages...


<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class AdminGuard
{
    /**
     * 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 = 'admin')
    {
        if (Auth::guard($guard)->guest()) {
            if ($request->ajax() || $request->wantsJson())
                return response('Unauthorized.', 401);
                return redirect()->route('admin');//redirect to admin login;
            }
        return $next($request);
    }
}

then you can use a redirect if authenticated already to admin dashboard


<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class AdminRedirect
{
    /**
     * 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 = 'admin')
    {
        if (Auth::guard($guard)->check()) {
            return redirect()->route('add');
        }

        return $next($request);
    }
}

new protected $routeMiddleware will look like

    protected $routeMiddleware = [
        'admin' => \App\Http\Middleware\AdminGuard::class,//protect guest routes
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'adminguest' => \App\Http\Middleware\AdminRedirect::class,//protect admin routes
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    ];

in your controller you can use a simple auth::attempt to log your admin in

        if (Auth::guard('admin')->attempt(['username'=>$request['username'],'password'=>$request['password']]))
          return redirect()->route('add');
          return redirect()->back();

***NOTE THAT AFTER ADMIN LOGIN OR AUTH::ATTEMPT == TRUE, USER LOGIN ROUTE IS STILL ACCESSIBLE BUT PROTECTED AND ALL ROUTES UNDER THE USER/AUTH MIDDLEWARE IS STILL PROTECTED