So basically, I'm using mass assignment for convenience. However I have a guarded field called "userid". I've made the separate code to insert into this field but for some reason I still get the error: SQLSTATE[HY000]: General error: 1364 Field 'userid' doesn't have a default value
Code:
$apply = Apply::create(
$request->all()
);
$apply->userid = Auth::user()->id;
$apply->save();
return redirect()->route('apply');
Model:
protected $guarded = ['userid'];
Thanks.
EDIT:
Still not fixed, any other solutions?
pass the userid field to the create function,
$apply = Apply::create(array_merge(
$request->all(),
[
"userid" => Auth::user()->id
])
);
$apply->save();
return redirect()->route('apply');
Related
I need validate if field already exist, throws error, but with this code no errors are triggered
Laravel 7
table: departamento
column: id int incremental
column: departamento varchar(150)
column: idPais int
store method
$this->validate($request, ['departamento' => Rule::unique('departamento','idPais')->where('departamento',$request->depto)->where('idPais',$request->pais)]);
Try with this too
$rules = [
'depto' => [Rule::unique('departamento')->where(function ($query) use ($request) {
return $query->where('departamento','=', $request->depto)->where('idPais','=', $request->pais);
}),]
];
$this->validate($request,$rules);
with this code, throws this error
$rules = [
'depto' => [Rule::unique('departamento')->where(function ($query) use ($request) {
return $query->where('departamento','=', $request->depto)->where('idPais','=', $request->pais);
}),]
];
$this->validate($request,$rules);
Thanks!!!
EDIT:
My bad, I need check two fields , departamento and idPais, thanks.
This is happening because of your field name. The unique rule will try to find a record with that column name set to the request value (in your case, depto, but your column name is departamento). When you are customising the query you are not overriding it, you are adding on top of this default behaviour. From the laravel docs:
By default, the unique rule will check the uniqueness of the column matching the name of the attribute being validated. However, you may pass a different column name as the second argument to the unique method:
With that in mind, you could either change the unique rule to set the column to departamento and not depto as per below, or change the request to send departamento attribute instead of depto:
$rules = [
'depto' => [Rule::unique('departamento', 'departamento')->where(function ($query) use ($request) {
return $query->where('idPais','=', $request->pais);
}),]
];
I have a many-to-many relationship between the User and Subscription tables in Laravel, as follows:
In Subscription.php:
public function users()
{
return $this->belongsToMany('App\User')->withTimestamps();
}
In User.php
public function subscriptions()
{
return $this->belongsToMany('App\Subscription')->withTimestamps();
}
I create a new subscription in Cashier (using Stripe) as follows:
$user->newSubscription($planname, $planname)->create();
(Note that the product and plan names are currently the same and the user's card is on record, hence the lack of a stripe token.)
But when I run this I get an error:
SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into subscriptions (name, stripe_id, stripe_plan, quantity, updated_at, created_at) values (projects, sub_EY1zRywZ1jUjLl, projects, 1, 2019-02-17 20:07:36, 2019-02-17 20:07:36))
I'm not sure if the relationship is causing the issue or whether it's my new subscription code. How do I fix this error?
UPDATE:
I've made the following change and I still get the same error:
$user->newSubscription($planname, $planname)->create(null,[
'user_id' => $user->id,
]);
UPDATE 2:
I've made the following change and the exact same error still occurs:
$id = Auth::id();
$user = User::find($id);
// $user = Auth::user();
Do you have the Billable trait added to your User model?
General error: 1364 Field 'user_id' doesn't have a default value.
According to this, I think you need to fill the user_id column with an id value via $id = Auth::id();
Taken from laravel documentation:
Additional User Details
If you would like to specify additional customer details, you may do so by passing them as the second argument to the create method:
$user->newSubscription('main', 'monthly')->create($stripeToken, [
'email' => $email,
]);
UPDATE
Could you try this one:
$id = Auth::id();
$user = User::find($id);
$user->newSubscription($planname, $planname)->create();
I am trying to insert data in a table using eloquent create method, But data which I have passed not coming in insert query generated by create method. Due to which I am getting a default value error.
Below are the code i have used
Model :
namespace App;
use Illuminate\Database\Eloquent\Model;
class PasswordReset extends Model
{
protected $fillable = ['email', 'token'];
}
Controller :
$content = ['email'=>'test#gmail.com', 'token'=>'1234'];
PasswordReset::create($content);
Error I am getting :
SQLSTATE[HY000]: General error: 1364 Field 'email' doesn't have a default value (SQL: insert into password_resets (updated_at, created_at) values (2018-09-25 16:16:45, 2018-09-25 16:16:45))
Why query in above error does not have 'email' and 'token' fields?
from your comment:
#cbaconnier, Thanks, After looking your comment. I have checked with my code and its having a __construct method without having any code within it and removing this resolve the issue.
If you want to use __construct() on the Model, you need to build it like this
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
// your code
}
I think you should create like this
PasswordReset::create([
'email'=>'test#gmail.com',
'token' => '1234'
]);
try this way :
$passwordReset = new PasswordReset();
$passwordReset->email = 'test#gmail.com';
$passwordReset->token = '12345';
$passwordReset->save();
try this i hope work for you :
PasswordReset::create([
'email'=>'test#gmail.com',
'token' => '1234']);
I'm trying to build a chat application using laravel echo and pusher, everything works but the data that returns to the databse is either null or the default value, here's the code
public function sendMessage(Request $request){
$conID = $request->conID;
$message1 = $request->message;
$user = Auth::user();
$fetch_userTo = DB::table('messages')
->where('conversation_id', $conID)
->where('user_to', '!=', Auth::user()->id)
->get();
$userTo = $fetch_userTo[0]->user_to;
$message = Message::create([
'user_from' => Auth::user()->id,
'user_to' => $userTo,
'conversation_id' => $conID,
'message' => $message1,
]);
if($message) {
$userMsg = DB::table('messages')
->join('users', 'users.id','messages.user_from')
->where('messages.conversation_id', $conID)->get();
broadcast(new MessagePosted($message))->toOthers();
return $userMsg;
}
}
NB: when i put insert() instead of create in the query the data goes through the database normally but there's an error in broadcasting
Have you tried to create a message like this? instead of using a model event?
$message = new Message;
$message->user_from = Auth::user()->id;
$message->$user_to = $userTo;
$message->conversation_id = $conID;
$message->message = $message1;
$message->save();
You have a lot more control this way, i.e
if($message->save()) { ... }
Or you could wrap the whole thing in a transaction?
Be sure your Message model allows the fields that you want to add in the $fillable array
Create method check fillable attributes into Laravel model. You have to write your all columns into fillable and then use create method.
Second solution is use Active Record technique. #Devin Greay answer is helpful to use Active record.
More information visit https://laravel.com/docs/5.6/eloquent#mass-assignment
I know this question has been asked earlier but i did not get relevant answer.
I want to know that how can i write a rule to check uniqueness of two columns. I have tried to write a rule like:
public $rules = array(
"event_id"=>"required",
"label"=>"required|unique:tblSection,label,event_id,$this->event_id",
"description"=>"required"
);
In my example i need to put validation so that one label could be unique for a single event id but may be used for other event id as well. For Example i want to achieve:
id event_id label description
1 1 demo testing
2 2 demo testing
In the rule defined above, somehow i need to pass current selected event_id so that it could check whether the label does not exist in the database table for selected event_id but i am getting syntax error like:
{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"syntax error, unexpected '\"'","file":"\/var\/www\/tamvote\/app\/modules\/sections\/models\/Sections.php","line":39}}
Note: I don't want to use any package but simply checking if laravel 4 capable enough to allow to write such rules.
The answer from Mohamed Bouallegue is correct.
In your controller for the store method you do:
Model::$rules['label'] = 'required|unique:table_name,label,NULL,event_id,event_id,' .$data['event_id'];
where $data is your POST data.
And for the update method you do:
$model = Model::find($id);
Model::$rules['label'] = 'required|unique:table_name,label,NULL,event_id,event_id,'.$data['event_id'].',id,id'.$model->id;
where $data is your PUT/PATCH data, $model is the record you are editing and id is the table primary key.
I didn't try this before but I think if you get the event_Id before validating then you can do it like this:
'label' => 'unique:table_name,label,NULL,event_id,event_id,'.$eventId
//you should get the $eventId first
If you want to declare your validation rules statically you can do this as well. It's not the most efficient since it checks the database for each value.
protected $rules = [
'user_id' => 'unique_multiple:memberships,user_id,group_id',
'group_id' => 'unique_multiple:memberships,user_id,group_id',
]
/**
* Validates that two or more fields are unique
*/
Validator::extend('unique_multiple', function ($attribute, $value, $parameters, $validator)
{
//if this is for an update then don't validate
//todo: this might be an issue if we allow people to "update" one of the columns..but currently these are getting set on create only
if (isset($validator->getData()['id'])) return true;
// Get table name from first parameter
$table = array_shift($parameters);
// Build the query
$query = DB::table($table);
// Add the field conditions
foreach ($parameters as $i => $field){
$query->where($field, $validator->getData()[$field]);
}
// Validation result will be false if any rows match the combination
return ($query->count() == 0);
});
Like Sabrina Leggett mentioned, you need to create your own custom validator.
Validator::extend('uniqueEventLabel', function ($attribute, $value, $parameters, $validator) {
$count = DB::table('table_name')->where('event_id', $value)
->where('label', $parameters[0])
->count();
return $count === 0;
}, 'Your error message if validation fails.');
You can call your validator by adding the following line to your rules:
'event_id' => "uniqueEventLabel:".request("label")
If you need more fields, you could add a new where clause to the sql statement.
(Source: edcs from this answer)
As you I was looking for hours to do that but nothing worked, I test everything ... suddenly the randomness of the doc I came across this:
'email' => Rule::unique('users')->where(function ($query) {
return $query->where('account_id', 1);
})
https://laravel.com/docs/5.5/validation#rule-unique
and it works perfectly and moreover it is very flexible :)