The scenario:
I need to pull data from table Properties that has relationship with city, neighborhood and category, passing all result through a collection that will "beautify" ugly columns to nice names.
So I do a select using method WITH:
//Query example
$result = Property::query();
$result = $result()->select('somefields')
->with('city')
->with('neighborhood')
->with('category')
->paginate($limit);
//Lets get results and use collection to rename ugly columns name:
PropertyResource::collection($result);
//It will rename fields based on this solution: https://laravel.com/docs/5.6/collections#method-toarray
What's my question:
PropertyResource only rename columns retrieved from table "Property". Tables "city","category" and "neighborhood" keep the native columns name.
How can I pass $result through other collections?
In collection method I can rename entire result this way:
<?php
namespace App\Http\Resources\v1;
use Illuminate\Http\Resources\Json\Resource;
class Property extends Resource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request
* #return array
*/
public function toArray($request)
{
return [
'id' => $this->SOMEFIELD,
'featured' => $this->SOMEFIELD,
'superFeatured' => $this->SOMEFIELD,
//THIS ONE COMES FROM A RELATIONSHIP
'description' => $this->propertyAdvertisement->SOMEFIELD,
'saleValue' => $this->SOMEFIELD,
'saleFormOfPayment' => $this->SOMEFIELD,
'vacationRentValue' => $this->SOMEFIELD,
'annualRentValue' => $this->SOMEFIELD,
'dormitories' => $this->SOMEFIELD,
'suites' => $this->SOMEFIELD,
'wc' => $this->SOMEFIELD,
'parkingSpaces' => $this->SOMEFIELD,
'coverImage' => $this->SOMEFIELD,
'coverDescription' => $this->SOMEFIELD,
'coverOrder' => $this->SOMEFIELD,
'features' => $this->SOMEFIELD,
'category' => $this->SOMEFIELD,
'subcategory' => $this->SOMEFIELD,
'city' => $this->SOMEFIELD,
'condominium' => $this->SOMEFIELD,
'neighborhood' => $this->SOMEFIELD,
'ref' => $this->SOMEFIELD,
'privateArea' => $this->SOMEFIELD,
'totalArea' => $this->SOMEFIELD,
'terrainSize' => $this->SOMEFIELD,
'finances' => $this->SOMEFIELD,
'ownerParcels' => $this->SOMEFIELD
];
}
}
This way only one collection can rename the entire result.
Related
$sql = DB::table('laravel_products')
->insert(array(
'name' => $name,
'price' => $price,
'qty' => $qty,
'description' => $description,
'uruu' => $uruu,
'garage' => $garage,
'duureg' => $duureg,
'tagt' => $tagt,
'talbai' => $talbai,
'haalga' => $haalga,
'tsonh' => $tsonh,
'shal' => $shal,
'tsonhtoo' => $ttsonh,
'hdawhar' => $bdawhar,
'lizing' => $lizing,
'utas' => $utas,
'email' => $email,
'hereg' => $hereg,
'bairshil' => $bairshil,
'bairlal' => $bairlal,
'ashig' => $ashigon,
'zahi' => $zahi,
'image' => $data
));
$lastInsertedID = $sql->lastInsertId();
When I try to insert its responses:
"Call to a member function lastInsertId() on bool"
I used insertGetId but its cant save multiple rows of pictures on mysql.
If you want to get the last inserted ID like that you can call that method on the PDO instance directly:
$id = DB::getPdo()->lastInsertId();
If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:
$id = DB::table('users')->insertGetId(
['email' => 'john#example.com', 'votes' => 0]
);
from : https://laravel.com/docs/5.8/queries#inserts
$data = new LaravelProducts(); //LaravelProducts is your Model Name
$data->name= $name; //here 'name' is your column name
$data->price= $price; //here 'price' is your column name
$data->qty= $qty; //here 'qty' is your column name
$data->description= $description; //here 'description' is your column name
..........
..........
$data->image= $image; //here 'image' is your column name
$data->save();
$lastInsertedId = $data->id;
You don't have to write a new query to collect last inserted id from database.
$laravel_product = DB::table('laravel_products')
->insertGetId( array(
'name' => $name,
'price' => $price,
'qty' => $qty,
'description' => $description,
'uruu' => $uruu,
'garage' => $garage,
'duureg' => $duureg,
'tagt' => $tagt,
'talbai' => $talbai,
'haalga' => $haalga,
'tsonh' => $tsonh,
'shal' => $shal,
'tsonhtoo' => $ttsonh,
'hdawhar' => $bdawhar,
'lizing' => $lizing,
'utas' => $utas,
'email' => $email,
'hereg' => $hereg,
'bairshil' => $bairshil,
'bairlal' => $bairlal,
'ashig' => $ashigon,
'zahi' => $zahi,
'image' => $data
)
);
foreach ($filenamesToSave as $filename) {
DB::insert('INSERT INTO laravel_products_images ( product_id, filename ) VALUES ( ?, ? )',[$laravel_product->id, $filename]);
return view('createproduct');
} // Foreach Closing
// Echo your inserted ID Like Below
echo $laravel_product->id;
It should be 100% working for you.
I tried with the code below. The record is inserted but the parent ID is not.
The last inserted ID of the parent table must also be inserted in the child table the same time when submit button is clicked.
Thanks.
Controller:
public function insert_doc_control_review(Request $request)
{
$form_data = array(
'comment' => $request->comment,
'assigned_to' => $request->assigned_to,
'revision' => $request->revision,
'file_id' => $request->file_id,
'attachment' => $request->attachment,
'phase_id' => $request->phase_id,
'review_date' => $request->review_date,
'due_date' => $request->due_date,
'completed_date' => $request->completed_date,
'user_id' => Auth::user()->id,
'doc_number' => $this->getNextDocRevNumber()
);
DocumentControlReview::create($form_data);
$lastId = DocumentControlReview::create($form_data);
$archive_data = array(
'user_id' => Auth::user()->id,
'iso_management_id' => $request->iso_management_id,
'phase_id' => $request->phase_id,
'document_control_review_id' => $request->document_control_review_id,
'initial_approval_id' => $request->initial_approval_id,
'review_id' => $request->review_id,
'final_approval_id' => $request->final_approval_id,
'awaiting_release_id' => $request->awaiting_release_id,
'release_id' => $request->release_id,
'project_id' => $request->project_id,
'folder_id' => $request->folder_id,
'file_id' => $request->file_id,
$lastId
);
DocumentRecordArchive::create($archive_data);
}
You have to write the code like below.
public function insert_doc_control_review(Request $request)
{
$form_data = array(
'comment' => $request->comment,
'assigned_to' => $request->assigned_to,
'revision' => $request->revision,
'file_id' => $request->file_id,
'attachment' => $request->attachment,
'phase_id' => $request->phase_id,
'review_date' => $request->review_date,
'due_date' => $request->due_date,
'completed_date' => $request->completed_date,
'user_id' => Auth::user()->id,
'doc_number' => $this->getNextDocRevNumber()
);
$lastId = DocumentControlReview::create($form_data);
$archive_data = array(
'user_id' => Auth::user()->id,
'iso_management_id' => $request->iso_management_id,
'phase_id' => $request->phase_id,
'document_control_review_id' => $lastId->id, // Parent ID
'initial_approval_id' => $request->initial_approval_id,
'review_id' => $request->review_id,
'final_approval_id' => $request->final_approval_id,
'awaiting_release_id' => $request->awaiting_release_id,
'release_id' => $request->release_id,
'project_id' => $request->project_id,
'folder_id' => $request->folder_id,
'file_id' => $request->file_id,
//'parent_id' => $lastId->id, there is document_control_review_id which I assume is the parent_id foreign column.
);
DocumentRecordArchive::create($archive_data);
}
look lastId is an object which holds the newly created data. you want to add this one's id in the child table. so use it's id attribute. i used parent_id as column name, change it according to your column name.
In case you have well formed relations in both models, another way can be:
$formData = [
'comment' => $request->comment,
'assigned_to' => $request->assigned_to,
'revision' => $request->revision,
'file_id' => $request->file_id,
'attachment' => $request->attachment,
'phase_id' => $request->phase_id,
'review_date' => $request->review_date,
'due_date' => $request->due_date,
'completed_date' => $request->completed_date,
'user_id' => Auth::id(),
'doc_number' => $this->getNextDocRevNumber(),
];
$documentControlReview = DocumentControlReview::create($formData);
$archiveData = [
'user_id' => Auth::id(),
'iso_management_id' => $request->iso_management_id,
'phase_id' => $request->phase_id,
'document_control_review_id' => $request->document_control_review_id,
'initial_approval_id' => $request->initial_approval_id,
'review_id' => $request->review_id,
'final_approval_id' => $request->final_approval_id,
'awaiting_release_id' => $request->awaiting_release_id,
'release_id' => $request->release_id,
'project_id' => $request->project_id,
'folder_id' => $request->folder_id,
'file_id' => $request->file_id,
];
$documentControlReview->documentRecordArchive()->create(archiveData);
For this working you need to have:
// DocumentControlReview::class
public function documentRecordArchive
{
return $this->hasOne(DocumentRecordArchive::class, 'parent_id');
}
// or
public function documentRecordArchives
{
return $this->hasMany(DocumentRecordArchive::class, 'parent_id');
}
// one of these two regarding which relation is set in business model 1:n or m:n
// DocumentRecordArchive::class
public function documentControlReview()
{
return $this->belongsTo(DocumentControlReview::class, 'parent_id');
}
Also, if child record in DB is mandatory, it is smart to set all transactions into try catch block:
try {
\DB::beginTransaction();
// make parent insertion
// make child insertion
// make another related DB actions if needed
// all good
\DB::commit();
} catch (\Exception $e) {
// nothing will be applied, something went wrong with one DB transaction
\DB::rollback();
// return redirect()->back()->with('error', $e->getMessage());
}
What is main thing I want to point here is that you don't need to use parentId value in array of child's data because it will be recognised as well and it is in some hand more secure - there is no way wrong parentId would be applied.
$firstTransaction->relationFromModel()->create($dataWithoutFirstTransactionIdBecauseItIsAlreadyAppliedThisWay);
Try this
public function insert_doc_control_review(Request $request)
{
$form_data = array(
'comment' => $request->comment,
'assigned_to' => $request->assigned_to,
'revision' => $request->revision,
'file_id' => $request->file_id,
'attachment' => $request->attachment,
'phase_id' => $request->phase_id,
'review_date' => $request->review_date,
'due_date' => $request->due_date,
'completed_date' => $request->completed_date,
'user_id' => Auth::user()->id,
'doc_number' => $this->getNextDocRevNumber()
);
$lastId = DocumentControlReview::create($form_data);
$archive_data = array(
'user_id' => Auth::user()->id,
'iso_management_id' => $request->iso_management_id,
'phase_id' => $request->phase_id,
'initial_approval_id' => $request->initial_approval_id,
'review_id' => $request->review_id,
'final_approval_id' => $request->final_approval_id,
'awaiting_release_id' => $request->awaiting_release_id,
'release_id' => $request->release_id,
'project_id' => $request->project_id,
'folder_id' => $request->folder_id,
'file_id' => $request->file_id,
'document_control_review_id' => $lastId->id
);
DocumentRecordArchive::create($archive_data);
}
I am able to import for 'users' table but I also need to import to pivot tables. Here's my code from my UsersController for importing to 'users' table, but is it possible to supply data to pivot tables like "user_company", "user_department" by importing? Can you show me a sample of importing to pivot tables? Anyways this is my code in importing.
if( Input::file('file_import') ) {
$path = Input::file('file_import')->getRealPath();
$inserts = [];
Excel::load($path,function($reader) use (&$inserts)
{
foreach ($reader->toArray() as $row){
$inserts[] = ['email' => $row['email'], 'username' => $row
['username'], 'password' => $row['password'], 'first_name' => $row['first_name'],'middle_name' => $row['middle_name'], 'last_name' => $row['last_name'], 'gender' => $row['gender'],
'civil_status' => $row['civil_status'], 'spouse' => $row['spouse'], 'religion' => $row['religion'],'emergency_no' => $row['emergency_no'],'previous_work' => $row['previous_work'],
'remarks' => $row['remarks'],'course' => $row['course'],'biometrics' => $row['biometrics'],'immediate_head' => $row['immediate_head'],'designation' => $row['designation'],'level' => $row['level'],
'emp_status' => $row['emp_status'],'dependents' => $row['dependents'],'date_hired' => $row['date_hired'],'regularization_date' => $row['regularization_date'],'remmitance_date' => $row['remmitance_date'],
'tin' => $row['tin'],'philhealth' => $row['philhealth'],'pagibig' => $row['pagibig'],'sss' => $row['sss'],'umid' => $row['umid'],'phone' => $row['phone'],'avatar' => $row['avatar'],
'address' => $row['address'],'country_id' => $row['country_id'],'role_id' => $row['role_id'],'birthday' => $row['birthday'],'status' => $row['status']];
}
});
}
}
if (!empty($inserts)) {
DB::table('users')->insert($inserts);
return back()->with('success','Inserted Record successfully');
}
There is a better way for this case, using Laravel Eloquent Relationships, but when using Laravel Database Query Builder you should get the last inserted id and to use it in next insert in "user_company", "user_department".
$userinsert = DB::table('users')->insert($inserts);
$insertedId = $userinsert->id;
$insertsusercompany = [
'user_id' => $insertedId,
'value1' => 'somedata1',
'value2' => 'somedata2'
]
$usercompany = DB::table('user_company')->insert($insertsusercompany);
... and the same for others tables, but you should use Eloquent Relationships, because it is much more easier.
This my request class rules.
return [
'title' => 'required|unique:event_cals,title',
'eventDate' => 'required|date|after:yesterday',
'venue' => 'required',
'time' => 'required',
'type' => 'required',
'unique:event_cals,eventDate,NULL,id,venue,$request->venue,time,$request->time'
];
I want to validate a rule like below.
'eventDate' && 'venue' && 'time' => 'unique'
There I need to check if there any row without same eventDate, venue and time altogether. Anyone knows how to declare such a rule?
This is the snapshot of db table.
Here is the possible solution:
<?php
return [
'title' => 'required|unique:event_cals,title',
'eventDate' => 'required|date|after:yesterday',
'venue' => 'required',
'time' => 'required',
'type' => 'required',
'event_date' => "unique:event_cals,event_date,NULL,id,venue,{$request->venue},time,{$request->time}",
];
I again want to highlight that; if you want that validator to work, you should make sure that the event_date and time should be correctly formatted.
An example unique check with additional wheres from our running project's update requests:
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
$id = $this->route('money');
return $rules = [
'name' => "required|string|min:3|max:255|unique:moneys,name,{$id},id,deleted_at,NULL,access,public",
];
}
Below is my model factory.
$factory->define(App\Business::class, function (Faker\Generator $faker){
return [
'name' => $faker->bs,
'slug' => $faker->slug,
'address' => $faker->streetAddress,
'phone_no' => $faker->phoneNumber,
'mobile_no' => $faker->phoneNumber,
'email' => $faker->companyEmail,
'website' => $faker->domainName,
'latitude' => $faker->latitude,
'longitude' => $faker->longitude,
'location' => $faker->city,
'business_days_from' => $faker->dayOfWeek,
'business_days_to' => $faker->dayOfWeek,
'description' => $faker->text,
'user_id' => $faker->factory(App\User::class),
];
});
and This my database seeder class
class DatabaseSeeder extends Seeder
{
public function run()
{
factory(App\Business::class, 300)->create();
}
}
But when I execute php artisan db:seed ...it does not work..
What should be the workaround here..any help would be appreciated..
you can get all ids using pluck (lists is depricated for laravel >= 5.2)
$userIds = User::all()->pluck('id')->toArray();
and get a random id for FK column:
'user_id' => $faker->randomElement($userIds)
You may also attach relationships to models using Closure attributes in your factory definitions.
'title' => $faker->title,
'content' => $faker->paragraph,
'user_id' => function () {
return factory(App\User::class)->create()->id;
}
I just found the workaround .. I replaced
'user_id' => $faker->factory(App\User::class),
with
'user_id' => $faker->randomElement(User::lists('id')->toArray()),
and that solves the problem for now..