Laravel authentication problem with multiple guards - laravel

im new to laravel and im trying to create login function with multiple guards. However when i insert the correct credentials in the form, it does not authenticate properly. I cant seem to find the problem with my login controller, any ideas?
This is my AdminLoginController
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AdminLoginController extends Controller
{
public function __construct()
{
$this->middleware('guest:admin');
}
public function showLoginForm()
{
return view('auth.admin-login');
}
public function login(Request $request)
{
// validate the form data
$this->validate($request, [
'admin_email ' => 'required|email',
'password' => 'required|min:8'
]);
//attempt to log the user in
if( Auth::guard('admin')->attempt(['admin_email'=>$request->admin_email, 'admin_password'=>$request->admin_password], $request->remember))
{
//if successful then send to their location
return redirect()->route('admin.dashboard');
}
//if fail redirect back to the login with the data
return redirect()->back()->withInput($request->only('admin_email','remember'));
}
}
This one is my form
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Admin-Login') }}</div>
<div class="card-body">
<form method="POST" action="{{ route('admin.login.submit') }}">
#csrf
<div class="row mb-3">
<label for="email" class="col-md-4 col-form-label text-md-end">{{ __('Email Address') }}</label>
<div class="col-md-6">
<input id="admin_email" type="email" class="form-control #error('admin_email') is-invalid #enderror" name="admin_email" value="{{ old('admin_email') }}" required autocomplete="admin_email" autofocus>
#error('admin_email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row mb-3">
<label for="password" class="col-md-4 col-form-label text-md-end">{{ __('Password') }}</label>
<div class="col-md-6">
<input id="admin_password" type="password" class="form-control #error('admin_password') is-invalid #enderror" name="admin_password" required autocomplete="current-admin_password">
#error('admin_password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row mb-3">
<div class="col-md-6 offset-md-4">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>
<label class="form-check-label" for="remember">
{{ __('Remember Me') }}
</label>
</div>
</div>
</div>
<div class="row mb-0">
<div class="col-md-8 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Login') }}
</button>
#if (Route::has('password.request'))
<a class="btn btn-link" href="{{ route('password.request') }}">
{{ __('Forgot Your Password?') }}
</a>
#endif
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
This one is the Model
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class Admin extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
protected $guard = 'admin';
public $timestamps = false;
/**
* The attributes that are mass assignable.
*
* #var array<int, string>
*/
protected $fillable = [
'admin_email',
'admin_password',
];
/**
* The attributes that should be hidden for serialization.
*
* #var array<int, string>
*/
protected $hidden = [
'admin_password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Edited: This is my route
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::prefix('admin')->group(function (){
Route::get('/login', [App\Http\Controllers\Auth\AdminLoginController::class, 'showLoginForm'])->name('admin.login');
Route::post('/login', [App\Http\Controllers\Auth\AdminLoginController::class, 'login'])->name('admin.login.submit');
Route::get('/', [App\Http\Controllers\adminController::class, 'index'])->name('home')->name('admin.dashboard');
});
my dd($request)
Illuminate\Http\Request {#43 ▼
#json: null
#convertedFiles: null
#userResolver: Closure($guard = null) {#260 ▶}
#routeResolver: Closure() {#268 ▶}
+attributes: Symfony\Component\HttpFoundation\ParameterBag {#45 ▶}
+request: Symfony\Component\HttpFoundation\InputBag {#44 ▶}
+query: Symfony\Component\HttpFoundation\InputBag {#51 ▶}
+server: Symfony\Component\HttpFoundation\ServerBag {#47 ▶}
+files: Symfony\Component\HttpFoundation\FileBag {#48 ▶}
+cookies: Symfony\Component\HttpFoundation\InputBag {#46 ▶}
+headers: Symfony\Component\HttpFoundation\HeaderBag {#49 ▶}
#content: null
#languages: null
#charsets: null
#encodings: null
#acceptableContentTypes: null
#pathInfo: "/admin/login"
#requestUri: "/admin/login"
#baseUrl: ""
#basePath: null
#method: "POST"
#format: null
#session: Illuminate\Session\Store {#300 ▶}
#locale: null
#defaultLocale: "en"
-preferredFormat: null
-isHostValid: true
-isForwardedValid: true
-isSafeContentPreferred: null
basePath: ""
format: "html"
}
This is my config/auth file
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'resident' => [
'driver' => 'session',
'provider' => 'residents',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
],
'residents' => [
'driver' => 'eloquent',
'model' => App\Models\Resident::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
'residents' => [
'provider' => 'residents',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
'admin' => [
'provider' => 'admins',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],

Related

Method Illuminate\Auth\SessionGuard::karyawan does not exist - Laravel 8

I'm having a problem with my Auth. So, I'm doing login but not using User models. I made my own models called Karyawan.
The error is:
Method Illuminate\Auth\SessionGuard::karyawan does not exist.
This is the public function on my controller:
public function admin()
{
return view('admin', [
"title" => "Admin",
"karyawan" => Karyawan::all()
]);
}
This is the auth.php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\Karyawan::class,
],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
my Karyawan models:
namespace App\Models;
use App\Models\Cuti;
use App\Models\Role;
use App\Models\Divisi;
use App\Models\Jabatan;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Karyawan extends Authenticatable
{
use HasFactory;
protected $guarded = ['karyawan_id'];
protected $table = 'karyawans';
public function scopeSearch($query, array $searchs) {
$query->when($searchs['search'] ?? false, function($query, $search) {
return $query->where('nama', 'like', '%' . $search . '%')
->orWhere('divisi_id', 'like', '%' . $search . '%')
->orWhere('jabatan_id', 'like', '%' . $search . '%')
->orWhere('agama', 'like', '%' . $search . '%')
->orWhere('nik', 'like', '%' . $search . '%');
});
}
public function role_id()
{
return $this->belongsTo(Role::class);
}
public function divisi()
{
return $this->belongsTo(Divisi::class);
}
public function jabatan()
{
return $this->belongsTo(Jabatan::class);
}
public function cuti()
{
return $this->hasMany(Cuti::class);
}
}
and this is the view I want to display:
<div class="dropdown">
<a href="#" class="d-flex align-items-center link-dark text-decoration-none dropdown-toggle" id="dropdownUser2" data-bs-toggle="dropdown" aria-expanded="false">
<img src="/images/avatar/avatar-2.png" alt="" width="32" height="40" class="rounded-circle me-2">
<strong>{{ auth()->karyawan()->nama }}</strong>
</a>
<ul class="dropdown-menu text-small shadow" aria-labelledby="dropdownUser2">
<li>
<form action="">
<button type="submit" class="dropdown-item">Logout</button>
</li>
</ul>
</div>
<main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
<h1 class="h2" style="position:absolute margin: auto auto"><p></p>Profil Pengguna</h1>
</div>
<center>
<img src="/images/avatar/avatar-2.png" style="width: 200px">
<p><h1>Selamat Datang, {{ auth()->karyawan()->nama }}</h1> </p>
<p> Divisi: {{ auth()->divisi()->nama_divisi }}</p>
<p> Jabatan: {{ auth()->jabatan()->nama_jabatan }}</p>
<p> Role: {{ auth()->role()->nama_role }}</p>
<p> Sisa cuti Anda: {{ auth()->karyawan()->sisa_cuti }}</p>
</center>
</div>
</main>
PS: The login auth is successful, not failed. the only problem is it can't display who is the user doing the login.

Form didn't insert data to database properly [Laravel][Eloquent]

I have problem with my code somewhere that make my data $request just didn't passed to my database table (?), I'm not sure what the problem is but every time I try to submit it just redirect back to my create blade view.But when I debug it using dd($request->all()); it have everything it need.
My table have 5 columns, id, book_id, member_id, user_id, borrow_date, return_date
My Model
protected $table = "borrow";
protected $guarded = [];
public $timestamps = false;
// Relationship Book
public function book()
{
return $this->belongsTo('App\Book');
}
// Relationship Member
public function member()
{
return $this->belongsTo('App\Member');
}
My Create Controller
public function create()
{
$book= Book::all();
$member= Member::all();
return view('borrow.create', compact('book', 'member'));
}
public function store(Request $request)
{
$this->validate($request,[
'book_id' => 'required',
'member_id' => 'required',
'user_id' => 'required',
'borrow_date' => 'required',
'return_date' => 'required',
'status' => 'required'
]);
Borrow::create([
'book_id' => $request->book_id,
'member_id' => $request->member_id,
'user_id' => Auth::user()->id,
'borrow_date' => $request->borrow_date,
'return_date' => $request->return_date,
'status' => 'borrowed',
]); return redirect('/borrow');
}
My Create View
<form action="/borrow" method="POST">
#csrf
<div class="form-group row">
<label class="col-sm-2 col-form-label">Book</label>
<div class="col-sm-10">
<select data-placeholder="Enter Book Data"
data-allow-clear="1" name="book_id" id="book_id">
<option></option>
#foreach($book as $value)
<option value="{{ $value->id }}">ISBN {{ $value->isbn }} -
{{ $value->title }} ({{ $value->year }})
</option>
#endforeach
</select>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Member</label>
<div class="col-sm-10">
<select data-placeholder="Enter Member Data"
data-allow-clear="1" name="member_id" id="member_id">
<option></option>
#foreach($member as $value)
<option value="{{ $value->id }}">{{ $value->name }}
#if ($value->gender == 'man')
(M) -
#else
(W) -
#endif
{{ $value->phone }}
</option>
#endforeach
</select>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Borrow Date</label>
<div class="col-sm-10">
<input type="date" class="form-control" name="borrow_date"
id="borrow_date">
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Return Date</label>
<div class="col-sm-10">
<input type="date" class="form-control" name="return_date"
id="return_date">
</div>
</div>
<button type="submit" class="btn btn-primary">Add</button>
</form>
dd($request->all());
array:5 [▼
"_token" => "pN3PPQGpT4jmLln59tY3HBiLj27fWgf65ioIYlv0"
"book_id" => "99"
"member_id" => "99"
"borrow_date" => "2021-09-01"
"return_date" => "2021-09-30"
]
Thanks! Sorry if my English and explanation is bad
You are trying to validate a user_id and a status presents in your $request but of course it doesn't.
$this->validate($request,[
'book_id' => 'required',
'member_id' => 'required',
'user_id' => 'required',
'borrow_date' => 'required',
'return_date' => 'required',
'status' => 'required'
]);
You are using Auth::user()->id as user_id and it isn't in $request
So, just remove 'user_id' => 'required', from validation. You also don't have status in your $request so you need to remove it too. It should be like this;
$this->validate($request,[
'book_id' => 'required',
'member_id' => 'required',
'borrow_date' => 'required',
'return_date' => 'required',
]);
Use fillable in Peminjaman model
protected $fillable = [
'id', 'book_id', 'member_id', 'user_id', 'borrow_date', 'return_date'
];
try to remove user_id and status from the validation, the request doesn't have these parameters, and you are validating them as required values.
$this->validate($request,[
'book_id' => 'required',
'member_id' => 'required',
'borrow_date' => 'required',
'return_date' => 'required',
]);
When using the create() method, you are using what is called massive assignment. As per docs https://laravel.com/docs/8.x/eloquent#mass-assignment:
...before using the create method, you will need to specify either a
fillable or guarded property on your model class. These properties are
required because all Eloquent models are protected against mass
assignment vulnerabilities by default.
Saying that, you have 2 options:
1 - Keep using create() method but define fillable property in your model
protected $fillable = ['id', 'book_id', 'member_id', 'user_id', 'borrow_date', 'return_date'];
2 - Use the save() method with not need to define fillable property:
$borrow = new Borrow();
$borrow->book_id = $request->book_id;
$borrow->member_id = $request->member_id;
$borrow->user_id = Auth::user()->id;
$borrow->borrow_date = $request->borrow_date;
$borrow->return_date = $request->return_date;
$borrow->status = 'borrowed';
$borrow->save();

Laravel 5.7.17 file validation issue

The example is based on Laravel's registration.
I have added following to register.blade.php:
<div class="form-group row">
<label for="file" class="col-md-4 col-form-label text-md-right">{{ __('Files') }}</label>
<div class="col-md-6">
<input type="file" id="files" name="files[]" multiple>
</div>
</div>
The method in RegisterController looks like this:
protected function validator(array $data)
{
$validator = Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'files.*' => ['required', 'file'],
]);
dd($validator->errors());
}
I'm trying to upload a PDF and a DOC file.:
MessageBag {#236 ▼
#messages: array:2 [▼
"files.0" => array:1 [▼
0 => "The files.0 must be a file."
]
"files.1" => array:1 [▼
0 => "The files.1 must be a file."
]
]
#format: ":message"
}
Must be a file? These are files...
just add enctype="multipart/form-data" to your form:
<form method="POST" action="{{ route('register') }}" enctype="multipart/form-data">
Try this :
protected function validator(array $data)
{
$validator = Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'files.*' => ['required', 'mimes:doc,docx,pdf,txt'],
]);
dd($validator->errors());
}

"Undefined index: password" laravel 5.6

i have three roles Hr,staff and admin... i use 3 middleware guards to guard each role.... but don't know why the staff(default web guard) won't allow me login... giving undefined index password error.
// controller function
public function logged(Request $request)
{
$this->validate($request,[
'email' => 'required|email',
'password' => 'required|min:6'
]);
if (Auth::guard('web')->attempt(['email'=>$request->email,
'password' => $request->password]))
{
return redirect()->intended(url('/home'));
}
Session::flash('message','Invalid Login details');
return redirect()->back()->withInput($request->only('email','remember'));
}
//my view
<div class="m-t-40 card-box">
<div class="panel-body">
<div class="login-form">
<h4><center>Login</center></h4>
<form action="{{route('login.submit')}}" method="POST" data-parsley-validate >
<input type="hidden" name="_token" value="{{csrf_token()}}"/>
<input type="text" name="email" placeholder="Email address" value="{{old('email')}}" required>
<input type="password" name="password" class="pass" placeholder="Password" required>
<span class="check-left"><input type="checkbox" name="remember" {{ old('remember') ? 'checked' : '' }}> Remember Me</span>
<span class="check-right">Forgot password?</span>
<div class="clearfix"></div>
<button class="btn btn-info btn-block" type="submit">Sign in</button>
<p class="center-block mg-t mg-b">Dont have and account?
Register here.
</p>
</form>
</div>
</div>
</div
// config/auth
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'admin'=> [
'driver' => 'session',
'provider' => 'admins',
],
'admin-api' => [
'driver' => 'token',
'provider' => 'admins',
],
'hr' => [
'driver' => 'session',
'provider' => 'hrs',
],
'hr-api' =>[
'driver' => 'token',
'provider' => 'hrs'
],
],
// screenshot of the error

why not update the picture? laravel 5.4

I can upload a picture, but when I try to update it, then there is no error. The file name changes in the database to the name of the new picture. And in the public folder the picture remains old and does not appear new.
I use: Intervention Image
What I did not understand, help please.
Controller: UploadController
use Illuminate\Http\Request;
use App\Post;
use Image;
use Storage;
use Faker\Provider\File;
public function update (Request $request, $id)
{
//validate
$this->validate($request, [
'title' => 'required|max:255',
'author' => 'required',
'text' => 'required',
'desc' => 'required',
'image' => 'required',
]);
$posts = Post::find($id);
$posts->title = $request->input('title');
$posts->author = $request->input('author');
$posts->text = $request->input('text');
$posts->desc = $request->input('desc');
$posts->image = $request->input('image');
//update image
if ($request->hasFile('image'))
{
$image = $request->file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('images/'. $filename);
Image::make($image)->resize(800, 400)->save($location);
$oldFilename = $posts->image;
//update db
$posts->image = $filename;
//delete old image
Storage::delete($oldFilename);
}
$posts->save();
return redirect('/');
}
View: edit.blade.php
<div class="container">
<form method="POST" action="{{ route('goUpdate', [$posts->id]) }}">
{{ csrf_field() }}
{!! method_field('patch') !!}
#if($posts)
<div class="form-group">
<br>
<label>title</label>
<input name="title" type="text" class="form-control" value="{{ $posts->title }}">
</div>
<div class="form-group">
<label>author</label>
<input name="author" type="text" class="form-control" value="{{ $posts->author }}">
</div>
<div class="form-group">
<label>text</label>
<textarea name="text" class="form-control" rows="7">{{ $posts->text }}</textarea>
</div>
<div class="form-group">
<label>desc</label>
<textarea name="desc" class="form-control" rows="5">{{ $posts->desc }}</textarea>
</div>
<div class="form-group">
<label>image</label>
<input type="file" name="image" class="form-control-file" value="" >
</div>
<div>
<input name="submit" type="submit" class="btn btn-primary" value="update"/>
back
</div>
#endif
</form>
<br>
filesystems.php
'disks' => [
'local' => [
'driver' => 'local',
'root' => public_path('images/'),
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
],
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
],
Try using this
$image = $request->file('image');
$filename = time() . '.' . $image->getClientOriginalName();
$path = public_path('events/' . $filename);
Image::make($image->getRealPath())->resize(300, 300)->save($path);
$event->image = 'events/' . $filename;
Hope this can help you

Resources