"Undefined index: password" Laravel 8.61.0 - php

I just checked using dd() that my variable $username and $password are not null.
But why Auth::attempt($user) is always return error message Undefined index: password
LoginController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
public function index()
{
return view('login/index', [
'title' => 'LOGIN'
]);
}
public function authenticate(Request $request)
{
$hashed_password = hash(config('var.default_hash'), $request['password']);
$request['password'] = $hashed_password;
$request->validate([
'username' => ['required'],
'password' => ['required'],
]);
$user = [
'username' => $request['username'],
'password_hash' => $request['password']
];
if (Auth::attempt($user)) {
$request->session()->regenerate();
return redirect()->intended('/');
}
return back()->with('fail', 'Login fail');
}
}
User.php
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class User extends Model implements Authenticatable
{
use HasFactory;
public $timestamps = false;
protected $fillable = ['name', 'username', 'password_hash', 'lang'];
/**
* The column name of the "remember me" token.
*
* #var string
*/
protected $rememberTokenName = 'remember_token';
/**
* Get the name of the unique identifier for the user.
*
* #return string
*/
public function getAuthIdentifierName()
{
return $this->getKeyName();
}
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->{$this->getAuthIdentifierName()};
}
/**
* Get the unique broadcast identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifierForBroadcasting()
{
return $this->getAuthIdentifier();
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password_hash;
}
/**
* Get the token value for the "remember me" session.
*
* #return string|null
*/
public function getRememberToken()
{
if (!empty($this->getRememberTokenName())) {
return (string) $this->{$this->getRememberTokenName()};
}
}
/**
* Set the token value for the "remember me" session.
*
* #param string $value
* #return void
*/
public function setRememberToken($value)
{
if (!empty($this->getRememberTokenName())) {
$this->{$this->getRememberTokenName()} = $value;
}
}
/**
* Get the column name for the "remember me" token.
*
* #return string
*/
public function getRememberTokenName()
{
return $this->rememberTokenName;
}
}
2021_09_24_081907_create_users_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('username');
$table->text('password_hash');
$table->String('lang');
$table->timestamp('created_at')->useCurrent();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}

I think you should create an array like this
if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
// Authentication was successful...
}
you need to change the username to email
then password_hash to password and you need to change your database user table.
https://laravel.com/docs/8.x/authentication#authenticating-users

Related

Laravel how to get back relationships from an array of ids

I have a table called addresses, it has a column name user_ids which is an array of the users who have that same address.
When I request to /api/addresses what it returns is {id:1,name:"lorem", user_ids:[1,2]}. I want it to return the users instead of their ids
this is the addresses model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Address extends Model
{
use HasFactory;
protected $fillable = [
'coordinates',
'title',
'description',
'user_ids',
];
protected $appends = ['user_ids'];
protected $casts = [
'user_ids' => 'array',
];
public function users()
{
return $this->belongsToMany(User::class,"addresses");
}
}
this is the create_table_addresses
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('addresses', function (Blueprint $table) {
$table->id();
$table->string('coordinates');
$table->string('title');
$table->string('description');
$table->json("user_ids");
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('addresses');
}
};
addresses controller
<?php
namespace App\Http\Controllers;
use App\Http\Requests\StoreAddressRequest;
use App\Http\Requests\UpdateAddressRequest;
use App\Models\Address;
class AddressController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return Address::with('users')->get();
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \App\Http\Requests\StoreAddressRequest $request
* #return \Illuminate\Http\Response
*/
public function store(StoreAddressRequest $request)
{
$address = Address::create($request->validated());
return response()->json($address, 201);
}
/**
* Display the specified resource.
*
* #param \App\Models\Address $address
* #return \Illuminate\Http\Response
*/
public function show(Address $address)
{
return $address;
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Models\Address $address
* #return \Illuminate\Http\Response
*/
public function edit(Address $address)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \App\Http\Requests\UpdateAddressRequest $request
* #param \App\Models\Address $address
* #return \Illuminate\Http\Response
*/
public function update(UpdateAddressRequest $request, Address $address)
{
$address->update($request->validated());
return response()->json($address, 200);
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\Address $address
* #return \Illuminate\Http\Response
*/
public function destroy(Address $address)
{
$address->delete();
return response()->json(null, 204);
}
}
My suggestion would be to use the database for this (since you're already using the with('addresses')).
(Documentation for that relationship starts here)
Migration:
Schema::create('address_user', function (Blueprint $table) {
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->integer('address_id')->unsigned()->index();
$table->foreign('address_id')->references('id')->on('addresses')->onDelete('cascade');
$table->primary(['user_id', 'address_id']);
});
User model:
use App\Models\User;
class Address extends Model {
public function users() {
return $this->belongsToMany(User::class);
}
}
Address model:
use App\Models\Address;
class User extends Model {
public function addresses() {
return $this->belongsToMany(Address::class);
}
}
Now you can use the relationship your application:
$address->users // Get all the users with that address
$user->addresses // Get all the addresses for the user
Address::with('users') // Get addresses with the users as an attribute
User::with('addresses') // Get users with the Address as an attribute
I am assuming that the response comes from a controller so then where you build you response, you need to append the user information.
Maybe something like
User::whereIn('id', [1,2])->get() ...
If you post the controller, then I can tell you exactly where to put this or how to do it better.

i want attach to tags but i get error Call to a member function attach() on null

i want create tag to my blog project | laravel
in models i make Many To Many relation in models but when i want to attach i get this error:
to a member function attach() on null
it is my blog model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use User;
class Blog extends Model
{
use HasFactory;
protected $fillable = [
'name',
'body',
];
/**
* Get the blog that owns the user.
*/
public function user()
{
return $this->belongsTo(User::class);
}
public function tags()
{
$this->belongsToMany(Tag::class);
}
}
and it is my tag model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Tag extends Model
{
use HasFactory;
public function blogs()
{
$this->belongsToMany(Blog::class);
}
}
and it is my tag and blog_tag table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
Schema::create('blog_tag', function (Blueprint $table) {
$table->integer('blog_id')->unsigned()->index();
$table->foreign('blog_id')->references('id')->on('tags')->onUpdate('cascade')->onDelete('cascade');
$table->integer('tag_id')->unsigned()->index();
$table->foreign('tag_id')->references('id')->on('blogs')->onUpdate('cascade')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('tags');
Schema::dropIfExists('blog_tag');
}
};
and it is my blog table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('blogs', function (Blueprint $table) {
$table->id();
$table->integer('user_id');
$table->string('name');
$table->longText('body');
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users')
->onUpdate('cascade')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('blogs');
}
};
and it is my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use function Ramsey\Uuid\v1;
use App\Models\User;
use App\Models\Blog;
use Illuminate\Support\Facades\Auth;
use DateTime;
class BlogController extends Controller
{
public function __construct() {
$this->middleware('auth')->only('create');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('welcome');
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('blog.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request, Blog $blog)
{
$validated = $request->validate([
'name' => 'required|max:100|min:3',
'body' => 'required|min:30',
]);
$name = $request->input('name');
$body = $request->input('body');
$blog->insert(['user_id' => Auth::id(),
'name' => $name,
'body' => $body,
'created_at' => new DateTime,
'updated_at' => new DateTime
]);
$blog->tags()->attach(1);
$request->session()->flash('sucsess', 'blog created succsessfully');
return back();
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($username, $blogName, User $user)
{
$user = $user->where('name', $username)->first();
$blog = $user->blogs->where('name', $blogName)->first();
// return $user->blogs->where('name', $blogName);
return view('blog.show', compact('user', 'blog'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($username, $blogName, User $user)
{
$user = $user->where('name', $username)->first();
$blog = $user->blogs->where('name', $blogName)->first();
$this->authorize('edit-blog', $user->id);
return view('blog.edit', compact('user', 'blog'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$validated = $request->validate([
'body' => 'required|min:30',
]);
Blog::find($id)->update([
'body' => $request->input('body')
]);
$request->session()->flash('sucsess', 'blog created succsessfully');
return back();
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy(Request $request, $id)
{
Blog::find($id)->delete();
$request->session()->flash('sucsess', 'blog deleted succsessfully');
return redirect()->route('dashboard');
}
}
I saw questions similar to yours on stack overflow, but none answered my question
pleas help my
try:
$newBlog = $blog->insert(['user_id' => Auth::id(),
'name' => $name,
'body' => $body,
'created_at' => new DateTime,
'updated_at' => new DateTime
]);
$newBlog->tags()->attach(1);

Laravel Many to many store to database

I want a system where I connect users with tasks and later I can assign tasks to different users from the amdin panel. My program doesn't work, it doesn't assign tasks to users. Later, I want to make sure that when a user logs in, they can only see their own tasks that an amdin has given them. Please help me what is the problem?!
Create user_task
Schema::create('user_task', function (Blueprint $table) {
$table->id();
$table->foreignId('task_id')->constrained()->onDelete('cascade');
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->timestamps();
});
Create users
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('avatar')->default('default.jpg');
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Create tasks
Schema::create('tasks', function (Blueprint $table) {
$table->id();
$table->string('alkalmazott');
$table->string('projekt')->default('-');
$table->string('feladat');
$table->date('hatarido');
$table->timestamps();
});
Task model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Task extends Model
{
use HasFactory;
protected $fillable = [
'alkalmazott', 'projekt' , 'feladat', 'hatarido'
];
public function projects(){
return $this->belongsToMany('App\Models\Project');
}
public function users()
{
return $this->belongsToMany('User', 'user_tasks');
}
}
User 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 Illuminate\Support\Facades\Hash;
use Laravel\Sanctum\HasApiTokens;
use Tasks;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
//public function setPasswordAttribute($password) {
// $this->attributes['password'] = Hash::make($password);
//}
public function jogoks(){
return $this->belongsToMany('App\Models\Jogok');
}
public function tasks()
{
return $this->belongsToMany('Task', 'user_tasks');
}
/* Check if the user has a role
* #param string $role
* #return bool
*/
public function hasAnyRole(string $role){
return null !== $this->jogoks()->where('name', $role)->first();
}
/* Check if the user has any given role
* #param array $role
* #return bool
*/
public function hasAnyRoles(array $role){
return null !== $this->jogoks()->whereIn('name', $role)->first();
}
}
Task controller (here i want to upload tasks)
<?php
namespace App\Http\Controllers;
use App\Models\Project;
use App\Models\Task;
use App\Models\User;
use Illuminate\Http\Request;
class TasksController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$tasks = Task::latest()->paginate(10);
return view('admin.tasks.index',compact('tasks'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('admin.tasks.create', ['users' => User::all()], ['tasks' => Task::all()]);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'alkalmazott' => 'required',
'projekt' => 'required',
'feladat' => 'required',
'hatarido' => 'required',
]);
Task::create($request->all());
return redirect()->route('admin.tasks.index')
->with('success','Product created successfully.');
}
/**
* Display the specified resource.
*
* #param \App\Models\Task $Task
* #return \Illuminate\Http\Response
*/
public function show(Task $Task)
{
return view('admin.tasks.show',compact('Task'));
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Models\Task $Task
* #return \Illuminate\Http\Response
*/
public function edit(Task $Task)
{
return view('admin.tasks.edit',compact('Task'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\Task $Task
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Task $Task)
{
$request->validate([
'alkalmazott' => 'required',
'projekt' => 'required',
'feladat' => 'required',
'hatarido' => 'required',
]);
$Task->update($request->all());
return redirect()->route('admin.tasks.index')
->with('success','Product updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\Task $Task
* #return \Illuminate\Http\Response
*/
public function destroy(Task $Task)
{
$Task->delete();
return redirect()->route('admin.tasks.index')
->with('success','Product deleted successfully');
}
}
And after i run my upload form, on the phpmyadmin the task has uploaded done but in the user_task table not working. Because its not working i cant display tasks for the users. Thank you for your replies!
You can use attach(), detach() or sync() functions in controller.
For example:
public function store(Request $request){
// ...
$task = Task::create($request->all());
$task->users->attach($request->users); // or you can use sync(), according to your needs and project
// $request->users must be an array like [1,3,10,21,28] etc.
// ...
}

Laravel JWT - Getting Unauthenticated with the valid login token

I am working on a simple JWT authentication system. User will get a token from login and when he passes the token, the user information will be given as the response. I have followed the procedure from: https://jwt-auth.readthedocs.io/en/develop/laravel-installation/ .
When I pass email and password to the login method I am able to get a token. But when I pass the token (to the me function) it returns 'Unauthorized'.
User Model:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* #return array
*/
public function getJWTCustomClaims()
{
return [];
}
}
```````
api.php (Route)
`````
Route::group([
'middleware' => 'api',
'prefix' => 'auth'
], function ($router) {
Route::post('login', 'AuthController#login');
Route::post('logout', 'AuthController#logout');
Route::post('refresh', 'AuthController#refresh');
Route::post('me', 'AuthController#me');
});
````
AuthController
```
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use App\User;
class AuthController extends Controller
{
/**
* Create a new AuthController instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login']]);
}
/**
* Get a JWT via given credentials.
*
* #return \Illuminate\Http\JsonResponse
*/
public function login()
{
$credentials = request(['email', 'password']);
if (! $token = auth()->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
//return response()->json(User::all());
}
/**
* Get the authenticated User.
*
* #return \Illuminate\Http\JsonResponse
*/
public function me()
{
return response()->json(auth()->user());
//return response()->json("hellllo");
}
/**
* Log the user out (Invalidate the token).
*
* #return \Illuminate\Http\JsonResponse
*/
public function logout()
{
auth()->logout();
return response()->json(['message' => 'Successfully logged out']);
}
/**
* Refresh a token.
*
* #return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
return $this->respondWithToken(auth()->refresh());
}
/**
* Get the token array structure.
*
* #param string $token
*
* #return \Illuminate\Http\JsonResponse
*/
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60
]);
}
}
```

Authentication laravel 4.2 cannot work

Authentication laravel can't work on my program. I have googled but not solve this. My program is
LoginController#auth
public function auth()
{
$username = Input::get('username');
$password = Input::get('pass');
if(Auth::attempt(array('id' => $username, 'password' => $password)))
{
echo "Work";
}
else
{
echo "Bad";
}
}
Authtable.php
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class Authtable extends Eloquent implements UserInterface, RemindableInterface
{
protected $table = 'authtable';
protected $hidden = array('password');
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getReminderEmail()
{
return $this->email;
}
public function getRememberToken()
{
return $this->remember_token;
}
public function setRememberToken($value)
{
$this->remember_token = $value;
}
public function getRememberTokenName()
{
return 'remember_token';
}
}
auth.php
'driver' => 'eloquent',
'model' => 'Authtable',
'table' => 'authtable',
And nullable remember_token(varchar(100)), password(varchar(60)) but still not work. Please give some solution.
I had a bad experience about that.
Composer dump-autoload to make sure model name is working.
Check that model name has no conflicts
Check 'authtable' column names. Is that columns include what you Input?'id' => $username, 'password' => $password

Categories