Laravel one-to-many save Carbon error - laravel

I have a class called SubjectData:
class SubjectData extends Model
{
protected $table = 'subject_datas';
protected $fillable = ['firstname','lastname','birthdate','birthcity','months'];
protected $dates = ['birthdate'];
public function setBirthdateAttribute($date)
{
// So we can add the time, not just he php date
$this->attributes['birthdate'] = Carbon::createFromFormat('d/m/Y', $date);
}
public function anamnesis() {
return $this->belongsTo('App\Anamnesis');
}
}
And I have a class called Anamnesis:
class Anamnesis extends Model
{
public function meetingTest() {
return $this->belongsTo('App\MeetingTest');
}
public function subject() {
return $this->belongsTo('App\Subject','subject_id','id');
}
public function subjectData() {
return $this->hasOne('App\SubjectData');
}
public function scholarHistory() {
return $this->hasOne('App\ScholarHistory');
}
public function familyHistory() {
return $this->hasOne('App\FamilyHistory');
}
public function psicodiagnosis() {
return $this->hasOne('App\Psicodiagnosis');
}
}
The store function of the SubjectController class works like this:
public function store(CreateSubjectRequest $request)
{
$input = $request->all();
// Let's generate the anamnesis of the subject
$anamnesis = Anamnesis::create();
$anamnesis->save();
$newSubjectData = $this->saveSubjectData($input);
$anamnesis->subjectData()->save($newSubjectData);
......
......
}
where the function called is:
public function saveSubjectData($input)
{
$subjectData['firstname'] = $input['firstname'];
$subjectData['lastname'] = $input['lastname'];
$subjectData['birthcity'] = $input['birthcity'];
$subjectData['birthdate'] = $input['birthdate'];
return SubjectData::create($subjectData);
}
The problem is with the "birthdate" property.
If i check the value of $newSubjectData (dd($newSubjectdata)) after the call $this->saveSubjectData($input) the value of the birthdate is exactly the one i set on the calendar in the frontside (and also in the db the value is correct)
If I put the dd($anamnesis->subjectData) after the call $anamnesis->subjectData()->save($newSubjectData) the result is the "today" date and also in the DB the value is not the one I set but the date of today.
I can't find the error
P.S. The calendar is inside a Vue template

I think the problem is that, the date must be an instance of Carbon or is properly formatted according to your database table. Try the following inside your saveSubjectData() method
$subjectData['birthdate'] = Carbon\Carbon::parse($input['birthdate']

I write down the answer but i thank John Aldrin that guided me in the right direction.
You have to put the timestamp('birthdate') AFTER the default timestamps of the migration table (so at the end of the migration table)
I don't know why. If someone knows please explain !

Related

Laravel hasMany relationship issue

I have a problem about table relationship in models. when I try to add hasMany relation there is an error popping up.
Call to undefined relationship [Plan100] on model [App\AllPlan].
This is the main table model places
protected $table = "places";
public $with = ["AllPlan"];
public function allplans()
{
return $this->hasMany("App\AllPlan");
}
And AllPlan table model
protected $table = "all_plans";
public function place()
{
return $this->belongsTo("App\Place");
}
No problem 'till here. I can see the AllPlan data inside the Places table on json response... But, the problem is popping up when I try to add hasMany relation into AllPlan table like below.
Now AllPlan table model looks like this.
protected $table = "all_plans";
public $with = [
"Plan100",
"Plan90",
];
public function place()
{
return $this->belongsTo("App\Place");
}
public function plan()
{
return $this->hasMany(
"App\Plan100",
"App\Plan90"
);
}
And the Plan100 table model look like this:
public function plan()
{
return $this->belongsTo("App\AllPlan");
}
But it's giving me an error. But I am not very sure where do I do wrong. Thank you.
Seems to me that you are trying to create two new relations, but this can't be done inside one function. Create two functions and refactor your code like this:
public function plan100()
{
return $this->hasMany(App\Plan100", 'foreign_key');
}
public function plan90()
{
return $this->hasMany(App\Plan90", 'foreign_key');
}

Trying to get property of non-object, but I can if I return it inmediatly

I have a good one here:
Im developing an API and im returning my values with the following code:
public function apigetDrugs(){
$arrayreturn= array();
foreach (Drug::all() as $drug){
$array=[
"pharma"=>$drug->pharma->name,
"id"=>$drug->id,
"code"=>$drug->code,
"CABMS_code"=>$drug->CABMS_code,
"CABMSDF_code"=>$drug->CABMSDF_code,
"name"=>$drug->name,
"concentration"=>$drug->concentration,
"presentation"=>$drug->presentation->name,
"container"=>$drug->container->name,
"previous_stock"=>$drug->previous_stock,
"added"=>$drug->added,
"added_transferred"=>$drug->added_transferred,
"exit"=>$drug->exit,
"exit_transferred"=>$drug->exit_transferred,
"extra"=>$drug->extra,
"user"=>$drug->user->name,
];
$arrayreturn[]=$array;
}
return $arrayreturn;
}
"Drug" model has relationships with Container, Presentation, User and Pharma. When I run my API I get the error "Trying to get property of non-object", so I decided to comment each line of code one by one and I found that I have the code running smoothly if I comment the pharma line, just like this:
public function apigetDrugs(){
$arrayreturn= array();
foreach (Drug::all() as $drug){
$array=[
//"pharma"=>$drug->pharma->name,
"id"=>$drug->id,
"code"=>$drug->code,
"CABMS_code"=>$drug->CABMS_code,
"CABMSDF_code"=>$drug->CABMSDF_code,
"name"=>$drug->name,
"concentration"=>$drug->concentration,
"presentation"=>$drug->presentation->name,
"container"=>$drug->container->name,
"previous_stock"=>$drug->previous_stock,
"added"=>$drug->added,
"added_transferred"=>$drug->added_transferred,
"exit"=>$drug->exit,
"exit_transferred"=>$drug->exit_transferred,
"extra"=>$drug->extra,
"user"=>$drug->user->name,
];
$arrayreturn[]=$array;
}
return $arrayreturn;
}
So I checked my relationships in the Pharma and Drug classes, nothing wrong that I can see with Drug:
class Drug extends Model
{
protected $guarded=[
"id",
"user_id"
];
use SoftDeletes;
protected $dates = ['deleted_at'];
//
public function user(){
return $this->belongsTo("App\User");
}
public function pharma(){
return $this->belongsTo("App\Pharma");
}
public function presentation(){
return $this->belongsTo("App\Presentation");
}
public function unit(){
return $this->belongsTo("App\Unit");
}
public function container(){
return $this->belongsTo("App\Container");
}
}
Nor with Pharma:
class Pharma extends Model
{
//
protected $guarded=[
"id"
];
public function drugs(){
$this->hasMany("App\Drug");
}
public function user(){
$this->belongsTo("App\User");
}
}
However I found something strange. I found this code will run without an issue and display perfectly the string that is intended to show:
public function apigetDrugs(){
$arrayreturn= array();
foreach (Drug::all() as $drug){
dd($drug->pharma->name);
}
}
And it will even work if I replace "dd" function with "echo". Hope to hear what you think about this issue soon.
Luis
Found my problem, one of my seeds had an invalid drug_id value.

how to get last id when a row was insert in laravel eloquent in Model

I've used setNotification method of model by initial data from Controller within a variable $data as array. I have used self:: in this method instead of used table or Notification::save() or $obj->save(). by this way I don't know how to get Id which the last id after insert was done in laravel because I used $this->attributes that it is the protected variable in Model.
class Notification extends Model
{
protected $table = 'notification';
public $timestamps = true;
private $_data = false;
public function setNotification($data)
{
if (is_array($data)) {
$this->attributes = $data;
self::save();
}
}
}
Try something like $this->attributes[id] after save() is executed.
I suggest You to use create method instead and return created object, so then You can access id property.
public function setNotification($data)
{
if (is_array($data)) {
return $this->create($data);
}
return null;
}

Laravel4 - Saving a model with multiple relationships/foreign keys

I've tried to understand a process of saving a model with multiple relationships but I still can't figure out how to do it "kosher" way.
To begin with - I have an Event model that belongs to a category (Eventcat) and a Location:
// Event.php
class Event extends Eloquent {
protected $table = 'events';
public function location()
{
return $this->belongsTo('Location');
}
public function eventcat()
{
return $this->belongsTo('Eventcat');
}
public function users()
{
return $this->belongsToMany('User');
}
}
// Location.php
class Location extends Eloquent
{
protected $table = 'locations';
public function events()
{
return $this->hasMany('Event');
}
}
// Eventcat.php
class Eventcat extends Eloquent
{
protected $table = 'eventcats';
public function events()
{
return $this->hasMany('Event');
}
}
I've seeded the database with a few categories and locations and now I trying to get events saving work. I thought that the $event->eventcat()->associate( $eventcat ) would work but I got a Call to undefined method eventcat() error.
public function postCreateEvent() {
$event = new Event();
$eventcat = Eventcat::find( Input::get('event-create-eventcat[]') );
$location = Location::find( Input::get('event-create-location[]') );
$event->title = Input::get('event-create-title');
$event->description = Input::get('event-create-description');
$event->price = Input::get('event-create-price');
$event->start_date = Input::get('event-create-start_date');
$event->end_date = Input::get('event-create-end_date');
$event->eventcat()->associate( $eventcat );
$event->location()->associate( $location );
$event->save();
}
I've read the documentation, API and a few threads here but I still can't figure out the best way to deal with this.
Thanks for replies!
I would actually bet that you have a conflict in your class name. Laravel contains an Event class and I wonder if that isn't what's being called in your code. As a quick test, you could rename your class FooEvent and see if it works.
The best solution is probably namespacing your model (see http://chrishayes.ca/blog/code/laravel-4-methods-staying-organized for a quick intro) so that your model can still be called Event without conflicting with the builtin class.

Laravel Saving A Model And Relationships

I have the following Model:
class Movie extends Eloquent {
protected $primaryKey = "movie_id";
public function detail()
{
return $this->hasOne('Detail');
}
public function firstpage()
{
return $this->hasOne('Firstpage');
}
public function country()
{
return $this->belongsToMany('Countries','movies_countries','movie_id','country_id');
}
public function year()
{
return $this->hasOne('Years');
}
public function media() {
return $this->hasMany('Media');
}
}
This is the Model of interest:
class Years extends Eloquent {
protected $table = 'movies_years';
protected $primaryKey = "relation_id";
public function movie()
{
return $this->belongsTo('Movie');
}
The DBTable for years has a field "movie_year" and "movie_id"
So, I have following problem, or understanding issue:
I'm trying to update the Model Years with new Data, but can't seem the get it done. I tried the following:
$movies = Movie::find($tmp['movie_id']);
$movies->title = $tmp['title'];
$movies->title_product = $tmp['title_product'];
$movies->title_orginal = $tmp['title_original'];
$movies->year = array('movie_year' => $tmp['movieyears']);
$movies->push();
The eye is on the $movies->year row, everything else works fine.
I also tried something stupid like:
$movies->year() = array('movie_year' => $tmp['movieyears']);
I don't know how to update the Years Model, which has a relation with the Movie Model.
The offical way would be using attach, sync or associate methods. These methods are described at http://laravel.com/docs/eloquent-relationships#inserting-related-models
In your case, you'd have to do something like this:
$movies->year()->attach($tmp['movieyears']);
To remove the relation (not the Movie or Year), use detach().

Resources