Replicate using foreign key - Laravel - php

I am trying to replicate certain data in my DB and I followed the steps as in the following link. Laravel 4: replicate to table
However, I need to replicate some other data using only a foreign key.I tried to use the find() method to get my data but returned nothing.The where clause returns my data but in the form of array which isn't accepted by the replicate method.
Anhy idea what i am doing wrong and how can I replicate my other data?!
Code:
$item = Cv::find($cv_id);
// return $item;
$clone = $item->replicate();
unset($clone['created_at'],$clone['updated_at']);
$data = json_decode($clone, true);
Cv::create($data);
//Skills
// return $cv_id;
$skills = Skill::where('cv_id', $cv_id);
$cloneSkills = $skills->replicate();
unset($cloneSkills['created_at'],$cloneSkills['updated_at']);
$skillData = json_decode($cloneSkills,true);
Skill::create($skillData);

For replicating skills you should probably use:
$skills = Skill::where('cv_id', $cv_id)->get();
foreach ($skills as $skill) {
$cloneSkill = $skill->replicate();
unset($cloneSkill['created_at'], $cloneSkill['updated_at']);
$skillData = json_decode($cloneSkill, true);
Skill::create($skillData);
}
You need to use get() to get all data and because $skills is Collection you need to use loop to replicate each skill.

Related

how can get a specific value from database in using php laravel model

function subscriptionpack(Request $request)
{
$sub = subscription::all();
$details = $sub['details'];
dump('$details');
}
I can get all values from this code, but I can't get the specific field that named details. When I call dump($sub) it was shown all details, but the dump('$details') make an error that is undefined index:details
anyone can help me to correct this code?
You can use select method to select specific column data :
$sub = subscription::select('details')->get();
Or, you can do with on get() method as like :
$sub = subscription::get(['details']);
If you need single column from the result set use pluck
$subs = subscription::all();
$details = $subs->pluck('details')->toArray();
You can either loop over to your collection e.g
foreach($sub as $s){
dump($s->details)
}
or you can try something like.
$sub->first()->details
but this will give you only first details element from your collection.
First a model should be in singular, no spacing between words, and capitalised.
You should use Subscription::all(); not subscription::all();. You should read Laravel conventions
use App\Subscription;
..
function subscriptionpack(Request $request)
{
$sub = Subscription::all()->pluck('details');
dd($sub);
}

Laravel replicate multiple rows didn't work

I want to replicate multiple relational rows to the same table with the diff job id.
But it doesn't work.
Here is my code
$parentJobUnits = Unit::where('job_id',$jobId)->get(); //may be single or multiple rows for units.
$JobCopy = $job->replicate()->save(); //main job copied for new units.
$partsCopy = array_map(function(Unit $unit) use($JobCopy)
{
$newUnit = $unit->replicate();
$newUnit->job_id = $JobCopy->id;
return $newUnit->save();
}, $parentJobUnits);
The above code is not working for multiple row replication.
Try removing the save method which causes a true return and not the copied record
correct: $job->replicate();
incorrect: $job->replicate()->save();
otherwise I'd do something like...
$parentJobUnits = Unit::where('job_id',$jobId)->get();
foreach($parentJobUnits as $unit)
{
$unit->replicate()->save();
}
$CollageData= Collage::where('student_id',$student_id)->get();
foreach($CollageData as $key => $collage )
{
$collage->replicate()->save();
}
This Works for me.
replicate() function does not work on get() function. It only works with find() function.
$parentJobUnits = Unit::where('job_id',$jobId)->get();
foreach($parentJobUnits as $key => $value)
{
$new_unit = Unit::find($value->id)->replicate(); // $value->id is your primary key
$new_unit->save();
}
It will replicate the multiple rows.

Laravel: Where consult in a foreach loop not working

I dont know what am I doing wrong, I have a foreach loop and a where consult inside it and when I try to get the data through that object, it says that it's and non-object and I cant get the data.
public function actualizar_costo_promedio()
{
$empresas = Empresa::all();
$anteriores_exist = 0;
foreach ($empresas as $empresa) {
$producto = $empresa->productos()->where('producto_nombre_id', 1)->first();
$anteriores_exist += $producto->existencias;
}
}
If i do this, it gives me that error but if I change the where for only $producto = $empresa->productos()->first(); it works
I've made other tests with $empresa = Empresa::find(1); and after do the consult $producto = $empresa->productos()->where('producto_nombre_id', 1)->first(); and also it works, so I don't understand what it's wrong
So let me tell you what is wrong, this piece of code:
$empresas = Empresa::all();
returns a collection or an array of arrays.
Now when you are foreaching you are iterating over the Empresa, but then you are accessing a relationship
$empresa->productos()
which from the error I can tell that it's a one-to-many relationship since the error is happening because the relationship is returning you another collection and you are trying to access a property which throws the error.
But when you pick up the first item in collection you actually access the first array in that array containing all the arrays! Therefore this is working:
$producto = $empresa->productos()->where('producto_nombre_id', 1)->first();
So if you want to make it work you need another iteration inside the foreach, or as I can understand correctly you want to get the existing products foreach Empresa you could do:
$anteriores_exist = $empresas->map(function($row) {
$products = $row->productos()->where('id', 1)->get();
return $products->filter(function($row) {
return $row->existencias;
});
});

Binding pivot table with Laravel Form Builders using checkbox group

I'd like to bind my checkbox group Form::checkbox('services[]') with data from my pivot table but I'm having trouble doing so, I think this is because no key is being returned with service_id.
My data model is as follows:
Business
Service
Business_Service table to store many to many link.
Blade Template
#foreach($service as $service)
{!! Form::checkbox('services[]', $service->id, (in_array($service->id, $selected_services) ? true : false)) !!}
#endforeach
Controller
$service = Service::all();
$selected_services = Auth::user()->business->services()->get();
return view('signup.step2', compact('service', 'selected_services'));
When I return $selected_services I can see the following:
[{"id":2,"name":"Service
1","image":"picture.png","created_at":"2017-03-31
00:31:20","updated_at":"2017-03-31
00:31:20","pivot":{"business_id":103,"service_id":2}},{"id":3,"name":"Service
2","image":"picture.png","created_at":"2017-03-31
00:31:23","updated_at":"2017-03-31
00:31:23","pivot":{"business_id":103,"service_id":3}}]
I have tried changing $selected_services like this:
$selected_services = Auth::user()->business->services()->keyBy('service_id');
But this only returns one row and doesn't associate a key to the row as expected.
If you want to use inbuilt Laravel functions, then you could use the Collection::pluck function.
$businessServices = Auth::user()->business->services->pluck('id');
I can prepare another array instead of using the collection Eloquent returns but I was hoping there was some built-in function by Laravel I could use.
$service = Service::all();
$business_services = Auth::user()->business->services()->get();
$selected_services = [];
foreach ($business_services as $ss) {
$selected_services[] = $ss->pivot->service_id;
}
return view('signup.step2', compact('service', 'selected_services'));

How to get different queries (models) results with one statement? - laravel

Sorry if my title is confusing, not sure how to explain this within a line. Let's say I have a table with some columns and I have this
$model = Document::where('systemName', '=', $systemName)->where('ticketNumber', '=', ($nextTicketNumber))->get(); ticketNumber is unique where as there are quite a few systemNames
The above will get exactly what I want but I want more. I want an another array which will store all the rows under the same systemName. I know I can do this by doing
$allSystemNameModel = Document::where('systemName', '=', $systemName)
But is there a possible way to not having two variables and be easier?
No, you can't get both collections into one variable with one statement, however, you can create an array and store your results there:
$both = [];
$both['model'] = ...
$both['all'] = ...
UPDATE:
To avoid querying the database twice, you can use a first method that laravel provides us with.
$allSystemNameModel = Document::where('systemName', '=', $systemName);
$model = $allSystemNameModel->first(function ($doc) use ($nextTicketNumber) {
return $doc->ticketNumber == $nextTicketNumber;
});
$both['model'] = $model;
$both['all'] = $allSystemNameModel->all();
Note: Be sure to use use when working with php closures since $nextTicketNumber will be undefined otherwise.

Categories