Replies: 2 comments 7 replies
-
Random in tests is not a good idea. As it may fail randomly. That being said, you can extend laravel's Eloquent Builder using macro's. |
Beta Was this translation helpful? Give feedback.
4 replies
-
Something I do in most of my projects is build an <?php
declare(strict_types = 1);
namespace App\Models;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Eloquent\Model as EloquentModel;
use Illuminate\Support\Facades\Cache;
/**
* @mixin EloquentModel
* @mixin EloquentBuilder
*/
class Model extends EloquentModel
{
public static function getCachedValueFromId(int $id, string $value = 'name') : mixed
{
$tag = str(static::class)->lower()->afterLast('\\')->toString();
return Cache::tags('model_cache')->remember(
"${tag}.${id}.${value}",
now()->addWeek(),
static fn () => self::find($id)?->{$value},
);
}
public static function hasRowWithValue(string $field, int|string|float $value) : bool
{
return Cache::tags('data')->remember(
static::class . '.' . $field . '.' . $value,
now()->addDay(),
static fn() => self::where($field, $value)->exists(),
);
}
} That way, the Models in the project can just extend public static function firstRandom() : self|null
{
return self::inRandomOrder()->first();
} |
Beta Was this translation helpful? Give feedback.
3 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi there!
I'm currently seeding my database with fake data. In order to fill foreign ids I need to get any existing model and pass its id. And I found myself repeating same line for different models like
Maybe it would be nice to add something like?
User::firstRandom();
Beta Was this translation helpful? Give feedback.
All reactions