I'm trying to assign role to user when they attempt. But it gives me this error. I'm using updateOrCreate() because I want to use that method later to change user role
SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'where
clause' (SQL: select * from roles where (0 = user_id and 1 = =
and 2 = 10) limit 1)
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger("user_id")->index();
$table->string("role_name");
$table->foreign("user_id")->references("id")->on("users")->onDelete("cascade");
});
RegisterController
protected function create(array $data)
{
$user = user::create([
'name' => $data['name'],
'email' => $data['email'],
"username" => $data["username"],
'password' => Hash::make($data['password']),
]);
if ($user) {
$model = new Role();
$model->assignNewbieRole($user->id);
}
return $user;
}
Role model
public function assignNewbieRole($id)
{
$this->updateOrCreate(["user_id","=",$id],["role_name","=","newbie"]);
}
How do I fix this ?
You need to pass an associated array instead of individual values:
$this->updateOrCreate(["user_id" => $id], ["role_name" => "newbie"]);
The values have to be set using a associative array where the column name is the key and the value is the value you want to find/insert.
$this->updateOrCreate(
["user_id" => $id],
["role_name" => "newbie"]
);
Related
I've been trying to solve this problem for several days but can't figure out the solution.
Could you help me please?
Laravel UserController code:
public function login(Request $request){
$request->validate(
[
'email' => 'required',
'password' => 'required',
]
);
if (Auth::guard()->attempt([['email' => $request->input('email')], ['password' => $request->input('password')]])) {
$request->session()->regenerate();
$user = User::where('email', $request->input('email'));
if($user != null){
$user->isLogin = true;
$user->save();
return response()->json(['id'=>$user->id], 200);
}
return response()->json(['message'=>'User not found'],404);
}
return response()->json(['error' => 'Invalid credentials'],400);
}
React api fetch with axios:
const logIn=(e) =>{
e.preventDefault();
axios.post('/api/login', {
email: email,
password:password
}).then(response => {
if(response.status==200){
console.log(response.data)
dispatch(login(response.data.id))
}
}).catch(error=>{
console.log(error.message)
})
}
Laravel login in routs:
Route::post('/login', [UserController::class, 'login']);
Laravel log:
[2022-08-10 11:36:34] local.ERROR: SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'where clause' (SQL: select * from users where (0 = id) limit 1) {"exception":"[object] (Illuminate\Database\QueryException(code: 42S22): SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'where clause' (SQL: select * from users where (0 = id) limit 1) at C:\xampp\htdocs\socialmedia\vendor\laravel\framework\src\Illuminate\Database\Connection.php:742)
you are passing multidimensional array in where condition
Can you try changing this lines
if (Auth::attempt(['email' => $request->input('email'),
'password' => $request->input('password')])) {
//here we are getting the first value
User::where('email', $request->input('email'))->first()
You can see this doc for more info related to login https://laravel.com/docs/9.x/authentication#authenticating-users
I'm working on an :
edit.blade.php
where users can edit data and the update method of Controller goes here:
public function update(Request $request, $id)
{
$discountCode = DiscountCode::find($id);
$request->validate([
'code' => 'unique:discount_codes,code'.$discountCode->id,
'started_at' => 'required_if:timespan,TRUE',
'ended_at' => 'required_if:timespan,TRUE',
],
...
}
So as you can see the code must be uique in discount_codes table.
So I tried adding :
$discountCode->id
in order to ignore unique validation rule for the current data but it does not work out and returns this error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'code15' in
'where clause' (SQL: select count(*) as aggregate from
`discount_codes` where `code15` = GIGvJjp4PM)
15 is my data row id.
So what's going wrong here? How can I solve this issue?
Use Rule::class to create the rule and ignore specific id
use Illuminate\Validation\Rule;
//...
public function update(Request $request, $id)
{
$discountCode = DiscountCode::findOrFail($id);
$request->validate([
'code' => [Rule::unique('discount_codes')->ignore($id)],
'started_at' => 'required_if:timespan,TRUE',
'ended_at' => 'required_if:timespan,TRUE',
],
...
}
I'm trying to nake a simple to save a simple Product in my db but for a reason I don't understand, I get this error each time I try to save.
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'files' in 'field list'
The thing is that I don't have any Files column and I don't want to have one.
Here's my migration file :
public function up()
{
Schema::create('formations', function (Blueprint $table) {
$table->id();
$table->string('name')->unique();
$table->string('subtitle');
$table->text('description');
$table->integer('price');
$table->integer('category_id');
$table->integer('level_id');
$table->timestamps();
});
}
Here's my comtroller file :
public function store(Request $request)
{
$request->validate(([
'name' => 'required|string',
'price' => 'required',
'description' => 'required',
'subtitle' => 'required',
'category_id' => 'required',
'level_id' => 'required',
]));
Formation::create($request->all());
return redirect()->route('admin.formations.index')->with('success','Formation ajoutée');
}
I'm confused!
Edit :
Here's the dd of $request
array:8 [▼
"_token" => "AGHU3QcTxNEd29ZVJ2mNM1lGMwAHDMqbIQEG4XxU"
"name" => "Lh lU"
"price" => "125"
"category_id" => "1"
"level_id" => "2"
"subtitle" => "Inke hune us kogru wuwuvat kerudowe anuzti gosvili dutoc wiv dufeaba job. Vaamcoj zodli kecuh wu ri hari sisalal gajesma ate ihloef egkes li zu. Ezfaaw uzared c ▶"
"description" => "<p>gg<br></p>"
"files" => null
]
It says "files" => null, but I don't know where that Files field comes from.
Nothing in my migrations and nothing in the db (PhpMyAdmin).
Really strange!
There is a files in your request, so you get this error. You can save your query in this way, to prevent extra field :
$q = new Formation();
$q->name = $request->name;
$q->price = $request->price;
$q->description = $request->description;
$q->subtitle = $request->subtitle;
$q->category_id = $request->category_id;
$q->level_id = $request->level_id;
$q->save();
Use $request->validated() instead of $request->all()
public function store(Request $request)
{
// ...
Formation::create($request->validated());
// ...
}
I am trying to check to see if (a) column(s) is/are unique by using the Rule::unique('table')->where(function($query) use($x) {...}); functionality but when I pass this into my validator I am getting a strange error. What I think is happening is that it is trying to check if a value is equal in the where the statement that I provided but also a column that it THINKS is the unique ID column for the table but it is not so it is breaking.
protected function validator(array $data)
{
$uid = 660000000;
$rule = Rule::unique('member_record')->where(function ($query) use ($uid) {
return $query->where('uniqueID', $uid);
});
return Validator::make($data, [
'fullName' => ['required', 'string', 'min:2'],
'member_id' => [
'bail', 'required', 'Numeric', $rule,
'exists:new_benefits_member,member_id'
],
'email' => ['bail', 'required', 'email', 'confirmed', 'unique:user,email'],
'password' => [
'required', 'string', 'min:8', 'confirmed',
'regex:/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{8,}$/'
],
'terms' => ['required']
]);
}
However, then I am getting an error that looks like the following.
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'member_id' in 'where clause' (SQL: select count(*) as aggregate from member_record where member_id = 660000000 and (uniqueID = 660000000))
What my only assumption is that when I am passing data into the Validator::make($data... it is trying to compare the $rule with the $data array and it is messing it up. Let me know if you have any fixes that I can try out.
The problem here is that the Rule::unique() function can take 2 parameters as shown below
public static function unique($table, $column = 'NULL')
{
return new Rules\Unique($table, $column);
}
if column is left as 'NULL' then this will default to the name of the key in the validator::make($x, [] <--- array
as shown in this example.
protected function validator(array $data)
{
$uid = 660000000;
$rule = Rule::unique('member_record')->where(function ($query) use ($uid) {
return $query->where('uniqueID', $uid)->orwhere('client_member_id', $uid);
});
$data['foo'] = 0;
$validator = Validator::make($data, [
'foo' => [$rule]
]);
return $validator;
}
results in this response
Column not found: 1054 Unknown column 'foo' in 'where clause' (SQL: select count(*) as aggregate from member_record where foo = 0 and (uniqueID = 660000000 or client_member_id = 660000000))
If you would like to exclude "is equal to" in the first part of the where clause you would perform a unique check like this
'member_id' => ['unique:member_record,foo']
If you would like to add additional where clauses then you would want to do something like this
'member_id' => ['unique:member_record,foo,NULL,id,bar,' . $uid]
This will return SQL looking like this
select count(*) as aggregate from member_record where foo = 660000000 and bar = 660000000
I'm trying to use Auth::user()->id; and post them with another model under 'user_id' so I don't have to manually give users a 'user_id'.
I've checked and included the required files and I'm getting the users "id" from Users Table
$user_id = Auth::user()->id;
echo $user_id; //this is returning right user "id"
I'm having trouble calling variables and posting it to DB in controller functions any help would be fine.
public function store(Request $request)
{
$user_id = Auth::user()->id;
$this->validate($request, [
'token1' => 'required',
'token2' => 'required'
]);
$tokens = new Tokens([
'user_id' => $user_id,
'token1' => $request->get('token1'),
'token2' => $request->get('token2')
]);
$tokens->save();
return view('/home');
}
Post the User "id" from User table into Tokens table's "user_id" so I can work with models
Getting this error:
SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL
constraint failed: tokens.user_id (SQL: insert into "tokens"
("token1", "token2", "updated_at", "created_at") values (asddsadf,
sdfasdf, 2019-09-24 11:53:57, 2019-09-24 11:53:57))
My migration is:
$table->bigIncrements('id');
$table->integer('user_id');
$table->string('token1');
$table->string('token2');
$table->timestamps();
You should avoid filling the user_id in this way.
The error is thrown because user_id is not a fillable property. But the correct way to handle this is with the relationships.
So I suppose that Tokens has a belongsTo relation because of its user_id foreign key (that anyway should be an unsignedInteger column) and in your model you have something like:
public function user() {
return $this->belongsTo(User::class)
}
If you have a look at the offical documentation you will see that you should change your code in this way:
public function store(Request $request)
{
$this->validate($request, [
'token1' => 'required',
'token2' => 'required'
]);
$tokens = new Tokens([
// 'user_id' => $user_id, This is useless
'token1' => $request->get('token1'),
'token2' => $request->get('token2')
]);
// With this method you're going to set the user_id column
$token->user()->associate(auth()->user());
$tokens->save();
return view('/home');
}