В документации Laravel говорится, что laravel автоматически регистрирует политики при использовании правильного именования и структуры папок, но мои политики не регистрируются. Я пытался просмотреть детали проекта с пользователем, который не является владельцем проекта, и это работает, но функция в политике возвращает false.
/app/Policies/ProjectPolicy.php
<?php
namespace App\Policies;
use App\Models\Project;
use App\Models\User;
use Illuminate\Auth\Access\Response;
class ProjectPolicy
{
/**
* Determine whether the user can view any models.
*/
public function viewAny(?User $user): bool
{
return false;
}
/**
* Determine whether the user can view the model.
*/
public function view(User $user, Project $project): bool
{
return false;
}
/**
* Determine whether the user can create models.
*/
public function create(?User $user): bool
{
return true;
}
/**
* Determine whether the user can update the model.
*/
public function update(User $user, Project $project): bool
{
return $user->id === $project->user_id;
}
/**
* Determine whether the user can delete the model.
*/
public function delete(User $user, Project $project): bool
{
return $user->id === $project->user_id;
}
/**
* Determine whether the user can restore the model.
*/
public function restore(?User $user, ?Project $project): bool
{
return false;
}
/**
* Determine whether the user can permanently delete the model.
*/
public function forceDelete(?User $user, ?Project $project): bool
{
return false;
}
}
/приложение/Модели/Project.php
<?php
namespace App\Models;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
use HasFactory;
protected $fillable = [
'title',
'description',
'user_id'
];
public function timers()
{
return $this->hasMany(Timer::class);
}
/**
* Calculate the total time of all timers in the project.
* returns time in HH:MM:SS format
*/
public function totalTime()
{
$timers = $this->timers()->get();
$totalTimeSeconds = 0;
foreach ($timers as $timer) {
$startTime = Carbon::parse($timer->start_time);
$endTime = $timer->end_time ? Carbon::parse($timer->end_time) : Carbon::now();
$diff = $startTime->diffInSeconds($endTime);
$totalTimeSeconds += $diff;
}
$timeHours = sprintf('%02d', floor($totalTimeSeconds / 3600));
$timeMinutes = sprintf('%02d', floor(($totalTimeSeconds % 3600) / 60));
$timeSeconds = sprintf('%02d', $totalTimeSeconds % 60);
return $timeHours . ':' . $timeMinutes . ':' . $timeSeconds;
}
}
Также вы можете выполнять математические вычисления с датами с помощью Carbon. Создайте интервалы с помощью чего-то вроде $interval = $startTime->diffAsCarbonInterval(), а затем добавьте к общей сумме с помощью $total->add($interval). Получите значение HMS в конце с помощью $total->format(). carbon.nesbot.com/docs






В документации Laravel рассказывается о регистрации политик или, как упоминается в документе, Автоматическое обнаружение политик
Вместо ручной регистрации политик модели Laravel может автоматически обнаруживать политики, если модель и политика соответствуют стандартным соглашениям об именах Laravel. В частности, политики должны находиться в каталоге Policies, расположенном в каталоге, содержащем ваши модели, или выше него.
Это означает, что Laravel будет знать ваши политики без необходимости или без их регистрации, НО вы можете использовать свои политики по своему усмотрению.
В разделе Авторизация действий с использованием политик вы можете найти различные способы использования политик:
Например, используя такую модель пользователя:
public function update(Request $request, Post $post)
{
if ($request->user()->cannot('update', $post)) {
abort(403);
}
// Update the post...
}
Вы действительно используете политику в своем контроллере? Код модели здесь вообще не имеет значения.