I am a bit stuck with the mass assignment. I have an input field (datepicker) which needs to get modififies (apply the strtotime function) before inserting it to the database.
Is there a way to do that while using the mass assignment?
class Customer extends Ardent {
protected $table = 'customers';
public $autoPurgeRedundantAttributes = true;
public $autoHydrateEntityFromInput = true;
public $forceEntityHydrationFromInput = true;
protected $fillable = array(
'email',
);
}
If you just need to change the Input, you can do:
$input = Input::all();
$input['date'] = strtotime($input['date']);
Input::replace($input);
Related
I have a strange problem. I'm trying to update a database entry with the save function, but the changed columns only update sometimes but most times they do not change yet I don't get any errors.
This is the code in my update function:
public function editadvocatedetails(Request $request){
try {
##get original data
$oldclaimantdets = Clthirdparties::where('claimant_code',$request->claimant_code)->first();
// ##get new data
$claimant_dets = Clthirdparties::where('record_type',$oldclaimantdets->record_type)->where('code',$oldclaimantdets->code)->first();
$claimant_dets->name = $request->name;
$claimant_dets->record_type = $request->record_type;
$claimant_dets->claimant_type = $request->claimant_type;
$claimant_dets->e_mail=$request->e_mail;
$claimant_dets->id_no=$request->id_no;
$claimant_dets->pin_number = $request->pin_number;
$claimant_dets->mobile = $request->mobile;
// // dd($claimant_dets);
$claimant_dets->save();
// dd($claimant_dets);
$mm = $claimant_dets->getChanges();
$user = Auth::user()->user_name;
$process = 'Update Claimant Details';
$claimant_code = $request->claimant_code;
$yy = $this->log_data($mm,$claimant_dets,$user,$process,$claimant_code);
Session::flash('success,'.$request->name.' details has been updated');
return redirect()->back();
} catch (\Throwable $th) {
Session::flash('error,'.$request->name.' failed to be updated');
return redirect()->back();
}
}
My Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Clthirdparties extends Model
{
protected $connection = 'oracle';
protected $table='clthirdparties';
public $timestamps=false;
public $keyType = 'string';
public $primaryKey='claimant_code';
public $incrementing=false;
protected $guarded = [];
}
When I print the values before the save, I get the correct values for both the old and new data.
It looks like the save() doesn't execute. The redirect is executed.
I'm aware of the update() method, but I used this way for updating entries in my database a lot and until now I never had any problems and I don't get where the problem is.
In the meantime I have reverted to update() to run the update query to solve the problem. But I still want to know why it is happening?
Maybe someone has an idea?
Sometimes hmm..., save() method is formally dependent on $fillable attribute array in the model. So, try defining fillable attributes.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Clthirdparties extends Model
{
protected $connection = 'oracle';
protected $table='clthirdparties';
public $timestamps=false;
public $keyType = 'string';
public $primaryKey='claimant_code';
public $incrementing=false;
protected $guarded = [];
protected $fillable = ['name','record_type','claimant_type','e_mail','id_no','pin_number','mobile',] ; //include all your attributes here.
}
I have two tables with a one to many relationship - gratitude_journal_entries and self_gratitudes. Multiple self gratitudes (which are submitted as text entries by the user) can apply to 1 gratitude_journal_entry. The data is passed to these two tables via a form.
I am trying to store the self gratitude text entries in an array and then pass these to the self_gratitude table along with the foreign key from the gratitude_journal_entries table.
The problem I'm having is I'm not sure how to take the input from the array and store this in the self_gratitude column.
Here are the columns for the gratitude_journal_entries table
Here are the columns for the self_gratitudes table
Here are the models and the store method in my controller
class SelfGratitudes extends Model
{
protected $table = 'self_gratitudes';
public $primarykey = 'id';
public function gratitudeJournalEntries() {
return $this->belongsTo(GratitudeJournalEntry::class);
}
}
class GratitudeJournalEntry extends Model
{
protected $table = 'gratitude_journal_entries';
public $primarykey = 'id';
public $timestamps = true;
public function user() {
return $this->belongsTo('App\User');
}
public function selfGratitudes()
{
return $this->hasMany(SelfGratitudes::class);
}
public function store(Request $request)
{
$this->validate($request, [
]);
$gj_entry = new GratitudeJournalEntry;
$gj_entry->user_id = auth()->user()->id;
$gj_entry['entry_date'] = date('Y-m-d H:i');
$self_gratitudes = $request->has('self_gratitudes') ? $request->get('self_gratitudes') : [];
$tj_entry->save();
$gj_entry->selfGratitudes()->sync($self_gratitudes);
return redirect('/dashboard')->with('success', 'You submitted a new journal entry');
}
If you want to keep array in database you can use casting on your columns:
laravel document
class SelfGratitudes extends Model
{
protected $casts = [
'self_graitude' => 'array',
];
protected $table = 'self_gratitudes';
public $primarykey = 'id';
public function gratitudeJournalEntries() {
return $this->belongsTo(GratitudeJournalEntry::class);
}
}
Part of data can not be acquired when Eloquent object is set to Json.
I use command artisan make:Auth, and customized users table.
Specifically, I thought that I did not need to delete the email column once,but since it became necessary, I added it again.
These operations use a migration file.
I got all the data of users table and returned it with Json.
But email is not output.
class UserController extends Controller
{
public function index() {
return User::all();
}
}
Even using json_encode did the same thing.
It exists when use this
$user = User::all();
$userArray = array();
foreach ($user as $u){
$userArray[] = [
'name' => $u->name,
'email' => $u->email
];
}
return $userArray;
Why is not email being outputted?
(I rely on google translation)
Additional notes
Thanks to everyone for comment.
Comparing the output of json with dd(), password and remember_token were not output in addition to email.
Perhaps the email is private property, and private property is a mechanism that does not output JSON?
In that case, how can I change to public?
The User model looks like this
class User extends Authenticatable
{
use Notifiable;
use SoftDeletes;
protected $table = 'users';
protected $dates = ['deleted_at'];
protected $primaryKey = 'uuid';
protected $keyType = 'string';
public $incrementing = false;
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'email','remember_token',
];
~~~
}
I solved it myself.
I found that the column set here is not output to JSON.
protected $hidden = [
'password', 'email','remember_token',
];
It was a very simple thing....
try this:
return User::select('name', 'email')->get()->toArray();
I have a Question model like this:
class Question extends Model
{
use SoftDeletes;
protected $primaryKey = 'question_id';
protected $dates = ['deleted_at'];
protected $fillable = ['text', 'code', 'cat', 'answer', 'is_private', 'email', 'parent'];
public function setCodeAttribute ($value)
{
\Debugbar::info('hello');
do {
$code = rand(10000, 10000000);
$user_code = User::where('code', $code)->get();
} while (!$user_code->isEmpty());
return $this->attributes['code'] = $code;
}
}
I want to generate a random integer number and store that in code field on creation of a new instance of the model.
For that I wrote a mutator as you can see but it did not even run.
What is problem?
Well mutator itself do not run untill you don't call $question->code = $someValue.
What you need is observer and define saving method in it that will provide setting of the code attribute value in it like this:
public function saving (Operation $operation)
{
\Debugbar::info('hello');
do {
$code = rand(10000, 10000000);
$user_code = User::where('code', $code)->get();
} while (!$user_code->isEmpty());
return $operation->code = $code;
}
and of corse you need to delete the mutator from the model class as well.
I'm new to using Traits and having trouble saving the protected attributes of my trait within my eloquent model:
Here is my Route model:
namespace App\Models;
use Eloquent;
class Route extends Eloquent {
use CardTrait {
CardTrait::__construct as __CardConstruct;
}
public $timestamps = false;
protected $table = 'routes';
protected $primaryKey = 'id';
protected $visible = [
'name',
'description'
];
public function __construct(array $attributes = array())
{
$this->__CardConstruct($attributes);
}
//relationships follow
}
and here is the CardTrait trait:
namespace App\Models;
trait CardTrait {
protected $timesAsked;
protected $factor;
protected $nextTime;
public function __construct($attributes = array(), $timesAsked = 0, $factor = 2.5, $nextTime = null)
{
parent::__construct($attributes);
if (is_null($nextTime)) $nextTime = \Carbon::now()->toDateTimeString();
$this->factor = $factor;
$this->nextTime = $nextTime;
$this->timesAsked = $timesAsked;
public function answer($difficulty)
{
if($difficulty < 3)
$this->timesAsked = 1;
}
//other methods follow
}
In my controller I can use:
$route = new Route();
$route->name = "New Name";
$route->description = "New Description";
$route->answer(5);
$route->save();
name and description save fine, and although I have columns for timesAsked, factor and nextTime When I dd($route) I can see
protected 'timesAsked' => int 1
protected 'factor' => float 2.6
protected 'nextTime' => string '2015-04-15 21:36:53' (length=19)
so I know the methods of the Trait are working fine.
My question is how can I save these values with Eloquent so that these can be stored and retrieved from the database?
Thanks in advance.
Eloquent will store values in an internal attributes array. This is what is actually written to the database. It will not write values to the attributes array if they already exist as a data member on the model. Look into the __set and __get magic methods and how they are used in Illuminate/Database/Eloquent/Model
So long story short, remove the protected data members from the model.