The merge method doesn't work in voyager laravel - laravel

I override the Laravel controller but now i don't what's the problem is coz it show me that (Field 'lab_price' doesn't have a default value) I used the merge method when I debugged its good and has a value.
$val = $this->validateBread($request->all(), $dataType->addRows)->validate();
$l_price = DB::table('labs')
->where('id', $request->lab_id)
->value('price');
$request->merge(['lab_price' => $l_price])
->all();
$data = $this->insertUpdateData($request, $slug, $dataType->addRows, new $dataType->model_name());
Actually i have lab_price column in child table and i want to get the (price) from the parent table and store in the child table whenever the lab_name is selected from the fronted.
Also if this method doesn't possible here, then is it possible through laravel observer?
I also go through it but i didn't find join in observer??

Related

Join query in laravel with data manipulation send to view

I am having 2 tables, users and profiledetails
I am able to run Join query and access the data and send to view.
But when I am manipulation the field 'dob' (date format) in profiledetails table. No Success, Please check the code below ,
webpagesConroller:
$users = DB::table('users')
->join('profiledetails', 'users.id', '=', 'profiledetails.user_id')
->select('users.*', 'profiledetails.dob')
->get();
$age = $users->dob->diffInYears(Carbon::now());
return view('webpages.index',compact('users'))->with($age);
View:
<li class="cate_head">Age : {{ $age}}</li>
Error:
Trying to get property of non-object
I have model Profiledetails added the mutators as below,
public function getAge(){
return $this->dob->diffInYears(Carbon::now());
}
public function getDOB(){
return $this->dob->format('d-m-Y');
}
Can I not use this method on another controller for Ex- webpagesController, If yes How.
Since you are using a raw query, the data returned is not an object but an array with the data.
Also you did not limit the query, meaning it could return multiple rows.
You'll probably need to get the data from the $users as:
//with the possibily of multiple rows. Index is the row which has to be used
$users[index]['dob']
//when you are sure it only returns one row
$users[0]['dob'] // or $users['dob'] not sure as of the moment
You want to check the differences with Carbon.
So you will probably need to make a Carbon object of the dob result and check it against the Carbon::now.
$age = Carbon::createFromFormat('Y-m-d', $users[0]['dob'])->diffForHumans();
// diffForHumans() uses the local time
Note that this only gets the age for one row (the index or the first because of [0]).
If you want to do it for every row use a for or foreach where you set the $users->age for every $user. But as these are not object/models but raw data, this will not work.
Hope this helps your question a bit

Laravel Collection Filter By Multiple Concatenated Unique Fields

I have a model download which has two three properties. Those properties are 'id' , 'user_id' , 'file_id'.
Whenever a user downloads a file a download record is created.
I want to grab all downloads that have both a unique file_id and unique user_id.
How is this accomplished.
A collection might come from a relationship and needs filtering afterward. Below is a tested working solution in laravel 5.7 and most probably in later versions also:
$unique = $collection->unique(function ($item)
{
return $item['brand'] . $item['model'];
});
Here is an article about this: http://laravel.at.jeffsbox.eu/laravel-5-eloquent-collection-methods-unique
You can use the groupBy method.
$downloads = DB::table('downloads')
->groupBy('file_id')
->groupBy('user_id')
->get();
OR
You can use the distinct method.
$downloads = DB::table('downloads')->distinct()->get();

Updating a pivot table in Eloquent

I've got a many to many relationship between a student and an institution_contact.
students should only ever have two institution_contacts and I have an attribute on the pivot table named type to be set as 1 or 2.
So, my pivot table looks like this:
institution_contact_student: id, institution_contact_id, student_id, type
I've run into difficulty in deciding how to approach the issue of adding/updating the pivot table. Let's say I have 100 students and I want to assign them a contact with the type of 1.
My current solution is to delete the contact then add it:
$students = Student::all(); // the 100 students
$contactId = InstitutionContact::first()->id; // the contact
foreach ($students as $student) {
// remove existing contact
$student
->institutionContacts()
->newPivotStatement()
->where('type', 1)
->delete();
// add new contact
$student
->institutionContacts()
->attach([$contactId => ['type' => 1]]);
}
However, I'm thinking that this is going to hit the database twice for each student, right? So would I be better off creating a model for the pivot table and removing all entries that matched the student id and the type then simply adding the new ones? Or would creating a model for the pivot table be considered bad practice and is there a better way of accomplishing this that I've missed?
Please note the reason I'm not using sync is because I'm relying on the type attribute to maintain only two contacts per student. I'm not aware of a way to modify an existing pivot without causing issues to my two contacts per student requirement.
Edit:
Instead of creating a model I could run the following code to perform the delete using DB.
DB::table('institution_contact_student') // the pivot table
->whereIn('student_id', $studentIds)
->where('type', 1)
->delete();
If I have understood your question correctly then you can use the updateExistingPivot method for updating your pivot table.But first of course you have to define the pivot in your relationship. For instance,
public function institutionContacts(){
return $this->belongsToMany('institutionContact')->withPivot('type');
}
after this, all you have to do is use the following code:
$student
->institutionContacts()
->updateExistingPivot($contactId, ["type" => 1]);
Hope this helps.

laravel4 update additional columns in pivot table

I'm trying to update additional column data in a pivot table in a many to many relationship.
I have two tables - reservation and resource linked with a pivot table. I can attach and am working with the model. However I'm struggling to update one of the additional columns in the pivot table.
I have an object: '$reservation' From that object I created another object $resources using:
$resources = $reservation->resource()->get();
I'm then iterating through $resources using a foreach loop as follows
foreach($resources as $resource ) {...}
I then want to update a column called gcal_id and am using the following:
$resource->pivot->gcal_id = "TEST";
$resource->save();
If I var_dump the model I can see the property exists to the correct value but in the database itself the entry is not being updated - so the save is not working
I have the columns listed in both sides of the relationship with this:
->withPivot('start', 'end', 'quantity', 'product_id','gcal_id')
Given I have the resource object how can I update a column correctly in the pivot table and save to database?
Thanks
After that you set the attribute on the pivot:
$resource->pivot->gcal_id = "TEST";
You seem to save the resource and not the pivot:
$resource->save();
If you want the pivot to be saved, saving the resource is not enough. Call save on the pivot instead:
$resource->pivot->gcal_id = "TEST";
$resource->pivot->save();
An alternative instead of save method, is the method Illuminate\Database\Eloquent\Relations\BelongsToMany\updateExistingPivot()
$reservation->resource()->updateExistingPivot($resource_id, ['gcal_id' => 'TEST']);
Or
$reservation->resource()->updateExistingPivot([1, 4, 5, 6], ['gcal_id' => 'TEST']);
This work for me in Laravel 4.2

Doctrine toarray does not convert relations

I followed doctrine documnetation to get started. Here is the documentation.
My code is
$User = Doctrine_Core::getTable("User")->find(1);
when I access relations by $User->Phonenumbers, it works. When I convert User object to array by using toArray() method, it does not convert relations to array. It simply display $User data.
Am I missing something?
By using the find method you've only retrieved the User data which is why the return of toArray is limited to that data. You need to specify the additional data to load, and the best place to do this is usually in the original query. From the example you linked to, add the select portion:
$q = Doctrine_Query::create()
->select('u.*, e.*, p.*') // Example only, select what you need, not *
->from('User u')
->leftJoin('u.Email e')
->leftJoin('u.Phonenumbers p')
->where('u.id = ?', 1);
Then when toArray'ing the results from that, you should see the associated email and phonenumber data as well.
I also noticed an anomaly with this where if you call the relationship first then call the ToArray, the relationship somehow gets included. what i mean is that, taking your own eg,
$User = Doctrine_Core::getTable("User")->find(1);
$num= $User->Phonenumbers->office; // assumed a field 'office' in your phone num table
$userArray = $user->toArray(true);
In the above case, $userArray somehow contains the whole relationship. if we remove the $num assignment it doesn't.
am guessing this is due to doctrine only fetching the one record first, and it's only when you try to access foreign key values that it fetches the other related tables

Resources