<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* Получить данные пользователя, связанные с этим пользователем.
*/
public function userData()
{
return $this->hasOne(UserData::class);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class UserData extends Model
{
use HasFactory;
/**
* @var array<int, string>
*/
protected $fillable = [
'phone_number',
];
/**
* Получить пользователя, которому принадлежат эти данные.
*/
public function user()
{
return $this->belongsTo(User::class);
}
}
use App\Models\User;
use App\Models\UserData;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
DB::transaction(function () {
// 1. Создаем пользователя (User)
$user = User::create([
'name' => 'Вася Пупкин',
'email' => 'uasya@fsb.ru',
'password' => Hash::make('12345'),
]);
// 2. Создаем данные пользователя (UserData) и связываем их с пользователем
$user->userData()->create([
'phone_number' => '112',
]);
});
Applications should read a PDF File from its end.
PDF.js is fetching the entire PDF file from a server. Can it fetch only the required portions for rendering?
Actually, PDF.js is doing just that. PDF is a complicated format; in most of the cases, the vital data of a PDF document is located at the end. Depending on browser support and on what web server returns the HTTP Range Requests headers, PDF.js may automatically start using HTTP Range Requests to fetch not-yet-loaded portions of a PDF needed for rendering visible pages, so a document can be rendered without fully loading it.
<?php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
// 1. Создаем уникальный ключ для этого конкретного запроса
$lockKey = 'request_lock:' . md5(json_encode($_REQUEST));
// 2. Пытаемся захватить ключ на 10 секунд
// Эта команда атомарная: только один процесс из двух победит.
$isLockAcquired = $redis->set($lockKey, '1', ['nx', 'ex' => 10]);
if ($isLockAcquired) {
// КЛЮЧ НАШ! Делаем свою работу
try {
// ... обращаемся к стороннему сервису, запускаем worker.php или ваще что угодно ...
// отвечаем клиенту об успехе операции
http_response_code(200);
echo json_encode(['status' => 'success']);
} catch(\Throwable $e) {
// Освобождаем ключ для будущих запросов в случае ошибки, чтобы не ждать 10с для переотправки.
$redis->del($lockKey);
// отвечаем клиенту, что произошла ошибка
http_response_code(500);
echo json_encode(['status' => 'error']);
}
} else {
// КЛЮЧ УЖЕ КЕМ-ТО ЗАНЯТ. Ничего не делаем.
// Просто отвечаем клиенту, что все ок или что запрос дублируется.
http_response_code(429); // Too Many Requests
echo json_encode(['status' => 'error', 'message' => 'Request already in progress']);
exit;
}
powercfg - h off
написали коллеги, тоже обязательно ))могу вручную делать return в каждом методе своего API, но это не выглядит правильным
если структура изменится, мне придется менять весь свой код
return response()->api($code, $data);
Response::macro('api', function ($code, $data) {
return new ApiResponse($code, $data);
});
MAIL_MAILER=smtp
MAIL_HOST=localhost
MAIL_PORT=25
MAIL_ENCRYPTION=null
git update-index --assume-unchanged your-file
) -> добавить в .gitignore