John Davidson

php - Can i make my code shorter by removing copy pasted pieces

0 comments
Message:


I am working on a laravel project. here i have a table 'file' (id, title, desc_long, desc_short, file (like .pdf etc.), language_id) and some pivots (tags, roles)


i am able to filter these file's on, tags and language.


<?php

namespace App\Http\Livewire;

use App\Models\File;
use App\Models\File_Role;
use App\Models\File_Tag;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use Illuminate\Support\Facades\DB;

class ShowFile extends Component
{


protected $listeners = ['reloadFile'];
public function mount()
{
$id = Auth::user();
$role_id = $id->role_id;
$file_role = File_Role::where('role_id', '=', $role_id)->pluck('file_id');
$this->files = File::whereIn('id', $file_role)->get();
}

public function render()
{
return view('livewire.show-file');
}

public function reloadFile($tag_id, $query, $langs)
{

$this->files = File::query();

$id = Auth::user();
$role_id = $id->role_id;
$file_role = File_Role::where('role_id', '=', $role_id)->pluck('file_id');
$count = count($file_role);

if($tag_id != 0 && $langs != 0)
{
for ($i = 0; $i < count($file_role); $i++) {
$fileCount = File_Tag::where('tag_id', $tag_id)->where('file_id', '=', $file_role[$i])->pluck('file_id')->count();
$file[] = $fileCount > 0 ? File_Tag::where('tag_id', $tag_id)->where('file_id', '=', $file_role[$i])->pluck('file_id') : null;
}
$this->files = File::whereIn('id', $file)->where('language_id', $langs)->get();
} else if ($tag_id != 0) {
for ($i = 0; $i < count($file_role); $i++) {
$fileCount = File_Tag::where('tag_id', $tag_id)->where('file_id', '=', $file_role[$i])->pluck('file_id')->count();
$file[] = $fileCount > 0 ? File_Tag::where('tag_id', $tag_id)->where('file_id', '=', $file_role[$i])->pluck('file_id') : null;
}
$this->files = File::whereIn('id', $file)->get();

} else if($langs != 0) {
$this->files = File::whereIn('id', $file_role)->where('language_id', $langs)->get();

} else {
$this->files = File::whereIn('id',$file_role)->get();
}


if ($query) {
$this->files = $this->files->where('title', 'like', '%' . $query . '%')->get();
// $this->files = File::whereIn('id', '=', $file_role)->get();
}
}
}


but as you can see, i use the same FOR loop twice. is there a way to avoid copy pasting code like i did above here?



My Answer:
Yes, you can make your code shorter by removing copy-pasted pieces and using functions or loops to avoid repetition. You can create reusable functions for common tasks and use loops to iterate over arrays or collections instead of writing the same code multiple times. This will make your code more concise and easier to maintain.

Rate this post

4 of 5 based on 2366 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us