tutorial que español php laravel-5

php - que - laravel tutorial español



Cómo usar multi Auth en laravel 5.2 (3)

Necesita dos tablas, users y admins Ejecute el comando siguiente para crear una autenticación integrada.

php artisan make:auth

Dos modelos Usuarios (ya existen) y Administrador

<?php namespace App; use Illuminate/Foundation/Auth/User as Authenticatable; class Admin extends Authenticatable { }

Ahora abra config / auth.php y realice los siguientes cambios

''guards'' => [ ''web'' => [ ''driver'' => ''session'', ''provider'' => ''users'', ], ''admin'' => [ ''driver'' => ''session'', ''provider'' => ''admins'', ], ], ''providers'' => [ ''users'' => [ ''driver'' => ''eloquent'', ''model'' => App/User::class, ], ''admins'' => [ ''driver'' => ''eloquent'', ''model'' => App/Admin::class, ], ], ''passwords'' => [ ''users'' => [ ''provider'' => ''users'', ''email'' => ''auth.emails.password'', ''table'' => ''password_resets'', ''expire'' => 60, ], ''admins'' => [ ''provider'' => ''admins'', ''email'' => ''auth.emails.password'', ''table'' => ''password_resets'', ''expire'' => 60, ], ],

Crear un nuevo Middleware RedirectIfNotAdmin

<?php namespace App/Http/Middleware; use Closure; use Illuminate/Support/Facades/Auth; class RedirectIfNotAdmin { /** * 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(''/admin/login''); } return $next($request); } }

Cambios en Kernel.php

protected $middleware = [ /Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode::class, /Illuminate/Session/Middleware/StartSession::class, /Illuminate/View/Middleware/ShareErrorsFromSession::class, ]; protected $middlewareGroups = [ ''web'' => [ /App/Http/Middleware/EncryptCookies::class, /Illuminate/Cookie/Middleware/AddQueuedCookiesToResponse::class, ///Illuminate/Session/Middleware/StartSession::class, ///Illuminate/View/Middleware/ShareErrorsFromSession::class, /App/Http/Middleware/VerifyCsrfToken::class, ], ''api'' => [ ''throttle:60,1'', ], ]; protected $routeMiddleware = [ ''auth'' => /App/Http/Middleware/Authenticate::class, ''auth.basic'' => /Illuminate/Auth/Middleware/AuthenticateWithBasicAuth::class, ''guest'' => /App/Http/Middleware/RedirectIfAuthenticated::class, ''throttle'' => /Illuminate/Routing/Middleware/ThrottleRequests::class, ''admin'' => /App/Http/Middleware/RedirectIfNotAdmin::class, ];

Crea una nueva carpeta Http / Controller / Adminauth y copia los archivos de la carpeta Http / Controller / Auth

Abra el archivo Http / Controller / Adminauth / AuthController.php y realice los siguientes cambios

<?php namespace App/Http/Controllers/Adminauth; use App/Admin; use Validator; use App/Http/Controllers/Controller; use Illuminate/Foundation/Auth/ThrottlesLogins; use Illuminate/Foundation/Auth/AuthenticatesAndRegistersUsers; use Auth; class AuthController extends Controller { use AuthenticatesAndRegistersUsers, ThrottlesLogins; protected $redirectTo = ''/admin''; protected $guard = ''admin''; public function showLoginForm() { if (Auth::guard(''admin'')->check()) { return redirect(''/admin''); } return view(''admin.auth.login''); } public function showRegistrationForm() { return view(''admin.auth.register''); } public function resetPassword() { return view(''admin.auth.passwords.email''); } public function logout(){ Auth::guard(''admin'')->logout(); return redirect(''/admin/login''); } }

Crear una nueva carpeta Http / Controller / admin, copiar el archivo Controller.php en la carpeta de Http / Controller /

crear nuevo archivo Http / Controller / admin / employee.php

<?php namespace App/Http/Controllers/admin; use Illuminate/Http/Request; use Illuminate/Routing/Controller; use Auth; use App/Admin; class Employee extends Controller { public function __construct(){ $this->middleware(''admin''); } public function index(){ return view(''admin.home''); } }

pasar a recursos / vistas crear nueva carpeta recursos / vistas / copia administrativa

resources/views/auth, resources/views/layouts & resources/views/home.blade.php

y publique en resources/views/admin y abra cada archivo en la carpeta admin y agregue admin antes de cada ruta, ahora la ruta debería verse como

@extends(''admin.layouts.app'')

y tu Http / routes.php parece

<?php Route::get(''/'', function () { return view(''welcome''); }); Route::get(''/admin/login'',''Adminauth/AuthController@showLoginForm''); Route::post(''/admin/login'',''Adminauth/AuthController@login''); Route::get(''/admin/password/reset'',''Adminauth/PasswordController@resetPassword''); Route::group([''middleware'' => [''admin'']], function () { //Login Routes... Route::get(''/admin/logout'',''Adminauth/AuthController@logout''); // Registration Routes... Route::get(''admin/register'', ''Adminauth/AuthController@showRegistrationForm''); Route::post(''admin/register'', ''Adminauth/AuthController@register''); Route::get(''/admin'', ''Admin/Employee@index''); }); Route::group([''middleware'' => ''web''], function () { Route::auth(); Route::get(''/home'', ''HomeController@index''); });

Eso es abrir tu sitio en el navegador y comprobar y para el administrador tuiteurl / admin

Disfrutar....

¿Alguien sabe cómo usar multi authenticate en laravel 5.2!
Quiero usarlo, pero no sé cómo?
¿Alguien tiene un tutorial o proyecto que configure la autenticación múltiple?


Primero, creamos dos modelos: usuario y administrador

Luego, actualizamos el archivo config / auth.php:

return [ ''defaults'' => [ ''guard'' => ''user'', ''passwords'' => ''user'', ], ''guards'' => [ ''user'' => [ ''driver'' => ''session'', ''provider'' => ''user'', ], ''admin'' => [ ''driver'' => ''session'', ''provider'' => ''admin'', ], ], ''providers'' => [ ''user'' => [ ''driver'' => ''eloquent'', ''model'' => ''App/User'', ], ''admin'' => [ ''driver'' => ''eloquent'', ''model'' => ''App/Admin'', ], ], ''passwords'' => [ ''user'' => [ ''provider'' => ''user'', ''email'' => ''auth.emails.password'', ''table'' => ''password_resets'', ''expire'' => 60, ], ''admin'' => [ ''provider'' => ''admin'', ''email'' => ''auth.emails.password'', ''table'' => ''password_resets'', ''expire'' => 60, ] ] ];

Ahora, modifique la aplicación / Http / kernel.php:

protected $middleware = [ /Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode::class, /Illuminate/Session/Middleware/StartSession::class, /Illuminate/View/Middleware/ShareErrorsFromSession::class ]; protected $middlewareGroups = [ ''web'' => [ /App/Http/Middleware/EncryptCookies::class, /Illuminate/Cookie/Middleware/AddQueuedCookiesToResponse::class ], ''api'' => [ ''throttle:60,1'', ], ];

Crea LoginController y configura el siguiente código en él.

Nota: Debe crear páginas de inicio de sesión para ''usuario'' y ''administrador''. Luego debe enviar solicitudes de formularios de inicio de sesión a la función de controlador adecuada, es decir, userLogin() o adminLogin() .

namespace App/Http/Controllers; use Auth, Input; use App/User; use App/Admin; class LoginController extends Controller { public function userLogin(){ $input = Input::all(); if(count($input) > 0){ $auth = auth()->guard(''user''); $credentials = [ ''email'' => $input[''email''], ''password'' => $input[''password''], ]; if ($auth->attempt($credentials)) { return redirect()->action(''LoginController@profile''); } else { echo ''Error''; } } else { return view(''user.login''); } } public function adminLogin(){ $input = Input::all(); if(count($input) > 0){ $auth = auth()->guard(''admin''); $credentials = [ ''email'' => $input[''email''], ''password'' => $input[''password''], ]; if ($auth->attempt($credentials)) { return redirect()->action(''LoginController@profile''); } else { echo ''Error''; } } else { return view(''admin.login''); } } public function profile(){ if(auth()->guard(''admin'')->check()){ pr(auth()->guard(''admin'')->user()->toArray()); } if(auth()->guard(''user'')->check()){ pr(auth()->guard(''user'')->user()->toArray()); } } }


En la mayoría de los casos, simplemente agrego un campo a la tabla de usuario llamado usertype y paso los valores apropiados como 0 = admin, 1 = usuario, etc.

Este enfoque ayuda a evitar el dolor de cabeza innecesario de crear diferentes roles o tipos de usuario.

Aunque esto puede no sonar ideal, pero ayuda a ahorrar mucho tiempo.