Laravel 5.4 elequent create method generate wrong query - laravel

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']);

Related

Laravel mass assigning guarded fields

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');

eloquent get all row of a table and edit a field

I'm a newbie on laravel and I'm trying to use Eloquent to edit a field for all rows of a MySQL table.
So I create that:
<?php
namespace App\Http\Controllers;
use App\Mining;
use DB;
class FrontendController extends Controller{
public function cronDiff(){
$basic = GeneralSettings::first();
$row = Mining::all()->whereStatus(1)->get();
foreach ($row as $coins){
$code = Mining::where('coin_code', $coins->coin_code)->get();
$risultato = difficolta($code);
DB::table['minings']->insert('coin_code' => $code);
}
}
}
And I have a table minings like this:
id->int
name->varchar
coin_code->varchar
coin_diff->varchar
status->tinyint
But I can't update coin_diff using the value of $risultato (taken from other function)
Can you help to find out where I'm wrong?
Thanks.
try to use ->update('coin_code' => $code); instead ->insert
I think this solution would be better:
$minings = DB::table('minings')->get();
$minings->coin_code = $code;
$minings->update();
It should work like that: Mining::update(['coin_code' => $code]) if you have conditions you can chain them before update.
Also, you need to have the columns on models $fillable property. So, i don't know what error do you get but it might be from that.
If you want to update then why are you using insert?!
If you want to update a single row then modify your code
DB::table['minings']->insert('coin_code' => $code);
to
$coins->update(['coin_code' => $risultato]);
And make sure that $risultato have string value

How to add data to additional column in pivot table in laravel

I'm trying to build an app in Laravel 5.3, I want to add additional column data in the pivot table. Following is my code:
My Users model:
public function relations()
{
return $this->belongsToMany('App\Plan')->withPivot('child');
}
My Plan model:
public function relations()
{
return $this->belongsToMany('App\User')->withPivot('child');
}
In my controller I'm fetching the user data from Auth::user(); and for plans and child element I'm getting through request. I want to store this to my pivot table. Following is the code which I tried in my controller:
$user = \Auth::user();
$plan_id = $request->plan_id;
$childid = $request->child_id;
$plan = App\Plan::find($plan_id);
$user->relations()->attach($plan, ['child' => $childid]);
Help me out in this.
You should use attach() like this:
$user->relations()->attach($plan_id, ['child' => $childid]);
Try the save method as:
$user->relations()->save($plan, ['child' => $childid]);
Docs
Both save and attach work. Just that attach will return null while save will return $user object when I try with tinker

custom `id` name using `insertGetId` fluent method of Laravel

According to Laravel's documentation:Inserts
Note: When using PostgreSQL the insertGetId method expects the auto-incrementing column to be named "id".
So, is there a workaround for a custom id name while using inserGetId. i.e.
$id = DB::table('users')->insertGetId(
['email' => 'john#example.com', 'votes' => 0]
);
You can use the Eloquent method Model::create() to return the object inserted, and obtain the object id, whatever his name is.
Try this:
$user = User::create(['email'=>'john#ecample.com','votes'=>0]);
$id = $user->custom_id;
This works if your User model is like:
class User extends Eloquent {
//This custom_id column needs to be of type serial in your table
protected $primaryKey = 'custom_id';
protected $fillable = ['email','votes'];
//...more code ...
}
I hope this works for you

Laravel Eloquent - $fillable is not working?

I have set the variable $fillable in my model. I wanted to test the update functionality, and I get this error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column '_method' in 'field list' (SQL: update positions set name = Casual Aquatic Leader, _method = PUT, id = 2, description = Here is my description, updated_at = 2014-05-29 17:05:11 where positions.client_id = 1 and id = 2)"
Why is this yelling at _method when my fillable doesn't have that as a parameter? My update function is:
Client::find($client_id)
->positions()
->whereId($id)
->update(Input::all());
Change following:
->update(Input::all());
to this (exclude the _method from the array)
->update(Input::except('_method'));
Update:
Actually following update method is being called from Illuminate\Database\Eloquent\Builder class which is being triggered by _call method of Illuminate\Database\Eloquent\Relations class (because you are calling the update on a relation) and hence the $fillable check is not getting performed and you may use Input::except('_method') as I answered:
public function update(array $values)
{
return $this->query->update($this->addUpdatedAtColumn($values));
}
If you directly call this on a Model (Not on a relation):
Positions::find($id)->update(Input::all());
Then this will not happen because fillable check will be performed within Model.php because following update method will be called from Illuminate\Database\Eloquent\Model class:
public function update(array $attributes = array())
{
if ( ! $this->exists)
{
return $this->newQuery()->update($attributes);
}
return $this->fill($attributes)->save();
}
write a parent class
class BaseModel extends Model
public static function getFillableAttribute(Model $model, $data){
$array = $model->getFillable();
$arr = [];
foreach ($array as $item){
if( isset($data["$item"])){
$arr["$item"] = $data["$item"];
}
}
return $arr;
}
I experienced this breaking after updating from Laravel 5.2 to 5.4 - I can't find anything in the documentation / migration guide that covers it.
As covered in this github issue the correct fix/use of Eloquent seems to be:
Positions::find($id)->fill(Input::all())->save();
To trigger the fillable check by laravel and then perist the changes.
You could also do this
$data = request()->all();
//remove them from the array
unset($data['_token'],$data['_method']);
//then
Client::find($client_id)
->positions()
->whereId($id)
->update($data);
This removes the _method and _token from the array

Resources