Skip to content

Instantly share code, notes, and snippets.

@Remonhasan
Created April 24, 2024 08:48
Show Gist options
  • Save Remonhasan/382f76906895288d52206eb5a5d71fd3 to your computer and use it in GitHub Desktop.
Save Remonhasan/382f76906895288d52206eb5a5d71fd3 to your computer and use it in GitHub Desktop.
Eloquent Query Scopes
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\Permission;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
class CategoryController extends Controller
{
public function destroy($categoryId)
{
$category = Category::getCategory($categoryId); // Eloquent Query Scopes applied
if (!empty($category)) {
$category->delete();
return redirect()->back()->with('success', 'Category deleted successfully!');
} else {
return back()->withErrors(['error' => 'Failed to delete category.']);
}
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
use HasFactory;
protected $fillable = [
'name_en',
'name_bn',
'status',
];
/**
* Get category by $categoryId
* Eloquent Query Scopes applied
* @param mixed $query
* @param mixed $categoryId
* @return void
*/
public function scopeGetCategory($query, $categoryId)
{
return $query->where('id', $categoryId)->first();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment