Error on user authentication in laravel - laravel

I am a beginner of laravel framework. I am now having problem in authentication in laravel 5.2. I tried but I can't find error.
Email and password is correct but it is redirecting to login page.
Here is my DB
+----+-------+-----------------+----------+-------+----------------+---------------------+---------------------+
| id | name | email | password | phone | remember_token | created_at | updated_at |
+----+-------+-----------------+----------+-------+----------------+---------------------+---------------------+
| 1 | Admin | admin#gmail.com | 111111 | | NULL | 2017-01-03 05:40:06 | 2017-01-03 05:40:06 |
+----+-------+-----------------+----------+-------+----------------+---------------------+---------------------+
Here is UserController
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\User;
use DB;
class UserController extends Controller
{
public function index()
{
if( !Auth::check() ) {
return view('user/index');
} else {
return view('user/profile');
}
}
public function login(Request $request)
{
if( Auth::attempt( array(
"email" => "admin#gmail.com",
"password" => "111111",
) ) ) {
return redirect('user/profile');
} else {
return redirect('user/login');
}
}
}

In Database you need to store password in encrypted format.Auth::attempt() will convert the password into encrypted form and compare with the password in database.
During data insertion into the database you need to use
bcrypt($password);

Related

Why registering user with fortify I got invalid user type?

In Laravel 8 app with inertiajs/vuejs2/fortify I try to run user register method wih axios
request(I need to make register wih confirmation code) from vue component :
makeRegisterStep1() {
console.log('makeRegisterStep1 this.registerForm::')
console.log(this.registerForm)
Window.axios.post('/register', this.registerForm)
.then(resp => {
console.log('makeRegisterStep1 resp::')
console.log(resp)
...
})
.catch(
function (error) {
console.error(error)
}
)
}, // makeRegisterStep1() {
bUT i GOT ERROR
POST http://127.0.0.1:8000/register 500 (Internal Server Error)
AND i SEE IN LOG FILE :
[2021-12-28 10:18:51] local.ERROR: Laravel\Fortify\Http\Controllers\RegisteredUserController::store(): Argument #2 ($creator) must be of type Laravel\Fortify\Contracts\CreatesNewUsers, App\Actions\Fortify\CreateNewUser given, called in /mnt/_work_sdb8/wwwroot/lar/photographers/li/vendor/laravel/framework/src/Illuminate/Routing/Controller.php on line 54 {"exception":"[object] (TypeError(code: 0): Laravel\\Fortify\\Http\\Controllers\\RegisteredUserController::store(): Argument #2 ($creator) must be of type Laravel\\Fortify\\Contracts\\CreatesNewUsers, App\\Actions\\Fortify\\CreateNewUser given, called in /mnt/_work_sdb8/wwwroot/lar/photographers/li/vendor/laravel/framework/src/Illuminate/Routing/Controller.php on line 54 at /mnt/_work_sdb8/wwwroot/lar/photographers/li/vendor/laravel/fortify/src/Http/Controllers/RegisteredUserController.php:51)
[stacktrace]
#0 /mnt/_work_sdb8/wwwroot/lar/photographers/li/vendor/laravel/framework/src/Illuminate/Routing/Controller.php(54): Laravel\\Fortify\\Http\\Controllers\\RegisteredUserController->store()
#1 /mnt/_work_sdb8/wwwroot/lar/photographers/li/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(45): Illuminate\\Routing\\Controller->callAction()
#2 /mnt/_work_sdb8/wwwroot/lar/photographers/li/vendor/laravel/framework/src/Illuminate/Routing/Route.php(262): Illuminate\\Routing\\ControllerDispatcher->dispatch()
I modified app/Providers/FortifyServiceProvider.php, but not Create user part :
<?php
namespace App\Providers;
use App\Actions\Fortify\CreateNewUser;
use App\Actions\Fortify\ResetUserPassword;
use App\Actions\Fortify\UpdateUserPassword;
use App\Actions\Fortify\UpdateUserProfileInformation;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;
use Illuminate\Validation\ValidationException;
use Laravel\Fortify\Fortify;
class FortifyServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
public function boot()
{
Fortify::loginView(function () {
return view('auth.login', [] );
});
Fortify::authenticateUsing(function (Request $request) {
$user = User::where('email', $request->email)->first();
$request = request();
if ($user && Hash::check($request->password, $user->password)) {
if ( $user->status === 'A') {
return $user;
}
else {
throw ValidationException::withMessages([
Fortify::username() => __("Your account is inactive"),
]);
}
}
});
Fortify::registerView(function () {
return view('auth.register', [] );
});
Fortify::createUsersUsing(CreateNewUser::class);
Fortify::updateUserProfileInformationUsing(UpdateUserProfileInformation::class);
Fortify::updateUserPasswordsUsing(UpdateUserPassword::class);
Fortify::resetUserPasswordsUsing(ResetUserPassword::class);
RateLimiter::for('login', function (Request $request) {
return Limit::perMinute(5)->by($request->email.$request->ip());
});
RateLimiter::for('two-factor', function (Request $request) {
return Limit::perMinute(5)->by($request->session()->get('login.id'));
});
}
}
hOW IT CAN BE FIXED ?
MODIFIED BLOCK :
No the pipeline is default,
and checking routes I see :
php artisan route:list
| Illuminate\Auth\Middleware\EnsureEmailIsVerified |
| | GET|HEAD | register | register | Laravel\Fortify\Http\Controllers\RegisteredUserController#create | web |
| | | | | | App\Http\Middleware\RedirectIfAuthenticated:web |
| | POST | register | generated::qWOIdxP9ML8fo3yR | Laravel\Fortify\Http\Controllers\RegisteredUserController#store | web |
| | | | | | App\Http\Middleware\RedirectIfAuthenticated:web |
| | GET|HEAD | test | test | App\Http\Controllers\HomeController#test | web |
| | DELETE | user | current-user.destroy | Laravel\Jetstream\Http\Controllers\Inertia\CurrentUserController#destroy | web |
| | | | | | App\Http\Middleware\Authenticate |
| | | | | | Illuminate\Auth\Middleware\EnsureEmailIsVerified |
| | GET|HEAD | user/confirm-password | password.confirm | Laravel\Fortify\Http\Controllers\ConfirmablePasswordController#show
Header of app/Models/User.php :
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Spatie\Permission\Traits\HasRoles;
use Spatie\Permission\Traits\HasPermissions;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
class User extends Authenticatable implements HasMedia //, MustVerifyEmail
{
use HasRoles;
use HasPermissions;
use HasFactory;
use Notifiable;
use TwoFactorAuthenticatable;
use InteractsWithMedia;
protected $fillable
= [
'name',
'email',
'status',
'password'
];
Originally that was laravel 8 admin starter kit based on bootstrap/jquery, without Fortify/Jetstream.
I installed Fortify manually with login service I need.
Also I use CreateNewUser class in my users seeder : :
app(CreateNewUser::class)->create([
'id' => 1,
'name' => 'Admin',
'email' => 'admin#site.com',
'password' => '11111111',
'status' => 'A',
], true, [PERMISSION_APP_ADMIN]);
What did I miss?
Thanks!

Laravel Route Model Binding Return False Owner of The Post

Good morning/afternoon/evening!
I have 2 model, User and post
User.php
public function getRouteKeyName()
{
return 'user_name';
}
public function posts()
{
return $this->hasMany(Post::class, 'by_id', 'id');
}
I have two records in users table
|--------------------------------------------|
| id | user_name | ... | ... |
|--------------------------------------------|
| 1 | megamanx | ... | ... |
| 2 | black_zero | ... | ... | // Edited
Post.php
public function getRouteKeyName()
{
return 'slug';
}
public function by()
{
return $this->belongsTo(User::class, 'by_id', 'id');
}
I have one record in posts table
|----------------------------------------------------|
| id | by_id | slug | ... |
|----------------------------------------------------|
| 1 | 1 | test-first-post | ... |
In my route
Route::group(['prefix' => '{user}', function () {
Route::get('/', function (User $user) {
return View::make('user.index', compact('user'));
});
Route::get('/{post}', function (User $user, Post $post) {
return View::make('post.index', compact('user', 'post'));
});
});
As you can see I use Route model binding for User user_name and for Post slug
So when I visit the route, ex :
127.0.0.1:8000/megamanx/test-first-post
// it return the correct owner
user megamanx is the owner of the post (test-first-post)
But, when I try the user param to other user, ex :
127.0.0.1:8000/black_zero/test-first-post
// Hey you don't own that post!
And the owner post name change to black_zero, but he didn't own that post
So how to solve this? I want when the user try to change the user_name, to something else, return 404. because only user megamanx own post test-first-post
I'm always open to critics, cause I want to be a better developer, if there's any wrong in method above (Route, model, etc), please correct me!, thank you (・∀・)ノ
Sorry for bad english ( ̄▽ ̄*)ゞ
Thanks in advance!

How to GroupBy in Relationship?

I have post table
| ID | TITLE | SLUG | CONTENT | COMMENTS_COUNT |
and i have post_reactions table
| ID | USER_ID | TYPE | POST_ID |
I want to make a relationship that what reactions that post have
You can directly do it by model.
public function postrelation()
{
return $this->hasMany(PostRelation::class)->groupBy('type');
}
Or
Post::with(['postrelation' => function($q){
$q->groupBy('type');
}])->get();
You can use callback function for grouping your relations describe at below.
Post::with(['post_reactions' => function($query){
$query->groupBy('TYPE');
}])->get();
You can make relation with the help of follwing syntax in the Model Class
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model {
/**
* Get the phone record associated with the user.
*/
public function phone(){
return $this->hasOne('App\Phone');
}
}

Laravel 5 returns string primary key as integer

I have a settings table in my database that looks like this:
| name | value | validation |
| site-name | Sample Site | max:255 |
| site-title | Sample Site | max:255 |
This is how my Setting model looks like:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Setting extends Model
{
protected $primaryKey = 'name';
protected $fillable = ['name', 'value'];
}
and the Controller.php file used for sharing the settings variable across all views:
<?php
namespace App\Http\Controllers;
use App\Setting;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesResources;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Auth;
class Controller extends BaseController
{
use AuthorizesRequests, AuthorizesResources, DispatchesJobs, ValidatesRequests;
protected $usr;
protected $settings;
public function __construct()
{
$this->usr = Auth::user();
view()->share('usr', $this->usr);
$this->settings = array();
$allSettings = Setting::all();
foreach ($allSettings as $setting)
$this->settings[$setting->name] = $setting->value;
print_r($this->settings);
view()->share('settings', $this->settings);
}
}
the print_r is used for debugging.
For some reason, the print_r outputs:
Array ( [0] => Sample Site )
instead of:
Array ( [site_name] => Sample Site )
It looks like $setting->name returns an integer instead of a string (the name column on the database is set as varchar).
Any ideas why it happens?
if its not integer use in model
public $incrementing = false;
Ok, I got this.
All I needed to do is to add this line to my Setting model:
public $incrementing = false;

Nested View not getting data from parent controller in Laravel 5.1

I'm building an Employee Management system and The employee part works good but when i try to create for family members for an employee i have a problem.
I was hoping i can create a family member for an employee in such a way
localhost/mysite/employees/5/families/create
Here are my files
P.S - I have omitted some of the code which i thought was irrelevant. For example, there are more than 30 employee fields that i save. For this question i just displayed the FirstName
routes.php
Route::resource('employees', 'EmployeesController');
Route::resource('employees.families', 'FamiliesController');
EmployeesController.php
<?php
namespace App\Http\Controllers;
use Carbon\Carbon;
use App\Employee;
use Illuminate\Http\Request;
use DB;
use App\Http\Controllers\Controller;
class EmployeesController extends Controller
{
public function index()
{
//Stuff that works well on employees/index
}
public function create()
{
//Stuff that works well on employees/create
}
public function store(Request $request)
{
//Stuff that works well
}
public function show(Employee $employee)
{
$employee=Employee::find($EmployeeID);
return view('employees.show', compact('employee'));
}
public function edit($EmployeeID)
{
$employee=Employee::find($EmployeeID);
return view('employees.edit',compact('employee'));
}
public function update(Request $request, $EmployeeID)
{
//Stuff that works well on employees/edit
}
}
Employee.php (Model)
<?php
namespace App;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Model;
class Employee extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $primaryKey = 'EmployeeID';
protected $fillable=[
'Name'
];
public function families()
{
return $this->hasMany('App\Family');
}
}
FamilyController.php (For now i only posted the index and create methods)
<?php
namespace App\Http\Controllers;
use App\Employee;
use App\Family;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class FamiliesController extends Controller
{
public function index(Employee $employee)
{
return view('families.index', compact('employee'));
}
public function create(Employee $employee)
{
return view('families.create', compact('employee'));
}
}
Family.php (Model)
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Family extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $primaryKey = 'FamilyID';
public function employees()
{
return $this->belongsTo('App\Employee');
}
}
Result from php artisan route:list
+--------+----------+------------------------------------------------+----------------------------+--------------------------------------------------+------------+
| Domain | Method | URI | Name | Action | Middleware |
+--------+----------+------------------------------------------------+----------------------------+--------------------------------------------------+------------+
| | GET|HEAD | employees | employees.index | App\Http\Controllers\EmployeesController#index | |
| | POST | employees | employees.store | App\Http\Controllers\EmployeesController#store | |
| | GET|HEAD | employees/create | employees.create | App\Http\Controllers\EmployeesController#create | |
| | PATCH | employees/{employees} | | App\Http\Controllers\EmployeesController#update | |
| | PUT | employees/{employees} | employees.update | App\Http\Controllers\EmployeesController#update | |
| | DELETE | employees/{employees} | employees.destroy | App\Http\Controllers\EmployeesController#destroy | |
| | GET|HEAD | employees/{employees} | employees.show | App\Http\Controllers\EmployeesController#show | |
| | GET|HEAD | employees/{employees}/edit | employees.edit | App\Http\Controllers\EmployeesController#edit | |
| | GET|HEAD | employees/{employees}/families | employees.families.index | App\Http\Controllers\FamiliesController#index | |
| | POST | employees/{employees}/families | employees.families.store | App\Http\Controllers\FamiliesController#store | |
| | GET|HEAD | employees/{employees}/families/create | employees.families.create | App\Http\Controllers\FamiliesController#create | |
| | PUT | employees/{employees}/families/{families} | employees.families.update | App\Http\Controllers\FamiliesController#update | |
| | DELETE | employees/{employees}/families/{families} | employees.families.destroy | App\Http\Controllers\FamiliesController#destroy | |
| | GET|HEAD | employees/{employees}/families/{families} | employees.families.show | App\Http\Controllers\FamiliesController#show | |
| | PATCH | employees/{employees}/families/{families} | | App\Http\Controllers\FamiliesController#update | |
| | GET|HEAD | employees/{employees}/families/{families}/edit | employees.families.edit | App\Http\Controllers\FamiliesController#edit | |
| | GET|HEAD | employees/{id}/delete | | App\Http\Controllers\EmployeesController#delete | |
+--------+----------+------------------------------------------------+----------------------------+--------------------------------------------------+------------+
When i navigate to http://localhost/mysite/public/employees/1/families/create i can see the create form but it's not getting the employee data. i did a vardump of $employee on that page and i was expecting to see the data for EmployeeID = 1 (as you can see from the url), but it was blank. Funny thing is that it's not throwing an error, it receives the $employee data passed from the controller but it a blank data.
So what could be the problem?
The create method on the familiescontroller.php isn't getting which Employee we are using. The following is how the create method is supposed to be on
public function create($EmployeeID)
{
$employee = Employee::findOrFail($EmployeeID);
return view('families.create')->with('employee', $employee);
}

Resources