fixes
This commit is contained in:
@@ -6,13 +6,32 @@ use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class Job extends Model
|
||||
{
|
||||
use SoftDeletes;
|
||||
|
||||
protected static function boot()
|
||||
{
|
||||
parent::boot();
|
||||
|
||||
static::creating(function ($job) {
|
||||
if (empty($job->slug)) {
|
||||
$job->slug = static::generateUniqueSlug($job->title, $job->company);
|
||||
}
|
||||
});
|
||||
|
||||
static::updating(function ($job) {
|
||||
if ($job->isDirty('title') && empty($job->slug)) {
|
||||
$job->slug = static::generateUniqueSlug($job->title, $job->company);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
protected $fillable = [
|
||||
'external_id',
|
||||
'slug',
|
||||
'title',
|
||||
'company',
|
||||
'description',
|
||||
@@ -187,4 +206,40 @@ class Job extends Model
|
||||
{
|
||||
return $query->where('company', 'LIKE', "%{$company}%");
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a unique slug for the job.
|
||||
*/
|
||||
public static function generateUniqueSlug(string $title, ?string $company = null): string
|
||||
{
|
||||
// Create base slug from title
|
||||
$baseSlug = Str::slug($title);
|
||||
|
||||
// Add company to slug if provided for better uniqueness
|
||||
if ($company) {
|
||||
$baseSlug .= '-' . Str::slug(Str::limit($company, 30, ''));
|
||||
}
|
||||
|
||||
// Limit slug length to avoid database issues
|
||||
$baseSlug = Str::limit($baseSlug, 200, '');
|
||||
|
||||
$slug = $baseSlug;
|
||||
$counter = 1;
|
||||
|
||||
// Check if slug exists and append counter if needed
|
||||
while (static::withTrashed()->where('slug', $slug)->exists()) {
|
||||
$slug = $baseSlug . '-' . $counter;
|
||||
$counter++;
|
||||
}
|
||||
|
||||
return $slug;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the route key for the model.
|
||||
*/
|
||||
public function getRouteKeyName(): string
|
||||
{
|
||||
return 'slug';
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user