How to delete multiple row from DB table by laravel? - php

I want to delete all comments from comments table.I did that by doing this but this is not the laravel way. Anyone answer the correct steps please .
$comments = Comment::where('post_id',$id)->get();
if(count($comments)>1)
{
$comment_id= [];
foreach ($comments as $i)
{
$comment_id[] = $i->id;
}
for($i=0;$i<count($comments);$i++)
{
Comment::find($comment_id[$i])->delete();
}
}
elseif (count($comments)==1)
{
$comments->delete();
}

Since each Eloquent model serves as a query builder, try this, all in one line:
Comment::where('post_id',$id)->delete();
Tested in tinker, works as expected, returns count of deleted rows.
Documentation: https://laravel.com/docs/5.3/queries#deletes

You can try the following approach:
public function deleteAll(Request $request)
{
$ids = $request->ids;
Comment::whereIn('id',explode(",",$ids))->delete();
}

DB::table('users')->whereIn('id', $ids_to_delete)->delete();
or
$org-products()->whereIn('id', $ids)->delete();

Collect only ids from your command like below and destroy by model.
$yourRaws = YourModel::where('name', 'Enver')->get();
...
YourModel::destroy($yourRaws->pluck('id')->toArray());
Enjoy Your Coding !

Related

How to filter child table selected using with clause in laravel

I am querying Item using following:
$itemdata = Item::with('itemimagedetails')
->with('variation')
->select('item.id', 'item.cat_id', 'item.item_name', 'item.item_description', 'item.brand', 'item.manufacturer', 'item.country_origin', 'item.ingredient_type', 'item.delivery_time', 'categories.category_name', 'item.category_unit')
->join('categories','item.cat_id','=','categories.id')
->where('item.id', $request['item_id'])->get()->first();
I want to filter variations using planid fetched from user table.
$plan = User::where('id', $request['user_id'])
I have tried:
if (count($itemdata->variation) > 0) {
$plan = User::where('id', $request['user_id'])->get();
foreach ($itemdata->variation as $key => $tag_name) {
if($tag_name == $plan['plan_id']) {
unset($itemdata->variation[$key]);
}
}
}
But then I get an error in the API calls.
Can someone please suggest best approach?
try using "having" statement search it in in laravel docs

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.

Work with foreach in Laravel: delete same values

I found way to delete duplicate values in the result but it doesn't work correctly. How to fix it?
I have next code:
public function getListPositionByApplication($app_id){
// $app_id = \Request::input('app_id');
$list = SparePartApplicationPositionProvider::where('app_id',$app_id)->with(['provider','application_position'])->orderBy('apos_id')
->get();
$aa=0;
foreach ($list as $value) {
if($value->apos_id==$aa){
$value->application_position->name_detail='----';
}
$aa = $value->apos_id;
Log::info($value->apos_id);
}
return $list;
}
Log::info give next information: 26,26,26,26,26,26,27,27,27,27,27,27,28
but $value->application_position->name_detail have '----' in all cases with the exception of last value
#Hussein is right, group by the common column and don't do a foreach. Let the Eloquent DB do the heavy lifting. Notice the callback where you include your second table.
$list = SparePartApplicationPositionProvider::where('app_id',$app_id)
->with(['provider','application_position' => function ($query){
$query->groupBy('name_detail');
}])
->orderBy('apos_id')
->get();
You can try collection unique() method.
https://laravel.com/docs/master/collections#method-unique

How do I remove duplicate rows with same column values in Laravel?

I'm trying to make a artisan command in Laravel to remove all venues that have the same address and leave the one with the lowest ID number (so first created).
For this I need to check 3 fields: 'street', 'house_number', 'house_number_addition'
This is how far I've got:
$venues = Venue::select('street', 'house_number', 'house_number_addition', DB::raw('COUNT(*) as count'))
->groupBy('street', 'house_number', 'house_number_addition')
->having('count', '>', 1)
->get();
foreach ($venues as $venue) {
$this->comment("Removing venue: {$venue->street} {$venue->house_number} {$venue->house_number_addition}");
$venue->delete();
}
Only the delete is not working but is also not giving an error.
To be able to delete an item, Eloquent needs to know it's id. If you make sure your models' id is queried, you can call delete() without issues.
In your query, however, that won't work because you have a GROUP_BY statement, so SQL doesn't allow you to select the id column (see here).
The easiest solution here is to utilize Eloquent's Collection class to map over the models, something like:
$uniqueAddresses = [];
Venue::all()
->filter(function(Venue $venue) use (&$uniqueAddresses) {
$address = sprintf("%s.%s.%s",
$venue->street,
$venue->house_number,
$venue->house_number_addition);
if (in_array($address, $uniqueAddresses)) {
// address is a duplicate
return $venue;
}
$uniqueAddresses[] = $address;
})->map(function(Venue $venue) {
$venue->delete();
});
Or, to make your delete query a little more efficient (depending on how big your dataset is):
$uniqueAddresses = [];
$duplicates = [];
Venue::all()
->map(function(Venue $venue) use (&$uniqueAddresses, &$duplicates) {
$address = sprintf("%s.%s.%s",
$venue->street,
$venue->house_number,
$venue->house_number_addition);
if (in_array($address, $uniqueAddresses)) {
// address is a duplicate
$duplicates[] = $venue->id;
} else {
$uniqueAddresses[] = $address;
}
});
DB::table('venues')->whereIn('id', $duplicates)->delete();
Note: the last one will permanently delete your models; it doesn't work with Eloquent's SoftDeletes functionality.
You could, of course, also write a raw query to do all this.

How to avoid adding duplicate of element.Laravel, PHP

Shortly, there are teachers and i have to attach them courses. Every course should be added once only(not twice). My code is working but only for element with id=1.And the other courses can be attached to a teacher more than once. I am writing the code in laravel. (php).
I can't uderstand why it is working only for the first element(course($id=1)).
Can you help me please. Where is my mistake?? Thank You in advance.
Here is my code. To One Teacher, many different courses should be attached. But not one course twice!
public function addCourse($id, Request $request) {
$teacher = Teacher::findOrFail($id);
if($teacher->has('courses')->where('id', $request->get('course_id'))->get()->isEmpty()) {
$teacher->courses()->attach($request->get('course_id'));
}
else {
flash()->error('This Course has been added already!')->important();
}
return back();
}
I believe there is an issue in how you are querying.
When you do this...
$teacher->has('courses')->where('id', $request->get('course_id'))
That ->where() is still looking at the teachers table, not the courses table. I think what you really want to do is use a whereHas to determine if the teacher has that course.
$hasCourse = Teacher::whereHas('courses', function($q) use ($request) {
// Here we can add constraints on the courses table
$q->where('id', $request->get('course_id'));
})->where('id', $id)->exists();
if (! $hasCourse) {
$course = Course::findOrFail($request->get('course_id'));
$course->teacher()->associate($id);
}
PROBLEM SOLVED. I used
$teacher->courses()->sync([$request->get('course_id')],$detaching =
false);
Finally i have this script:
> public function addCourse($id, Request $request) {
> $teacher = Teacher::findOrFail($id);
> $teacher->courses()->sync([$request->get('course_id')],$detaching =
> false);
>
> return back();
> }
Thank you all.
To attach a one to many
$teacher = Teacher::findOrFail($id);
$course = Course::findOrFail($request->get('course_id'));
$course->teacher()->associate($teacher);;
$course->save();

Categories