首页 > 解决方案 > 为 Laravel API 实施全局应用程序设置?

问题描述

我希望实现一些全局应用设置,例如应用名称、一周的第一天和其他功能标志。最终目标是让管理员通过 API 获取和编辑这些内容。

这样做最方便的方法是什么?我已经尝试过使用设置模型来存储键值对,但这对我来说没有意义,因为所需的设置应该是硬编码的并且不会改变,并且播种设置表听起来并不理想。提前致谢!

标签: laravelapisettings

解决方案


您可以从 Laravel 提供的配置函数中访问 App 名称。

$appName = config('app.name'); 
// This value is retrieved from .env file of APP_NAME=

如果你必须存储多个与星期相关的值,你可以创建一个新的配置文件 week.php

//config/week.php
return [
    ...
    'first_day_of_the_week' => 0
]; 

为了检索 first_day_of_the_week,您可以使用相同的函数配置

$firstDayOfTheWeek = config('week.first_day_of_the_week')

与其他基本标志类似,您可以创建一个新的配置文件。您可以稍后使用以下命令缓存您的配置变量。

php artisan config:cache

您还可以在 laravel 项目中的任何首选位置创建一个 Helper 类。我将助手类保存在 App\Helpers 中。

<?php

namespace App\Helpers;

use Carbon\Carbon;

class DateHelpers
{
    public const DATE_RANGE_SEPARATOR = ' to ';

    public static function getTodayFormat($format = 'Y-m-d')
    {
        $today = Carbon::now();
        $todayDate = Carbon::parse($today->format($format));
        return $todayDate;
    }
    ....
}

如果需要在 Laravel 项目中检索方法值,可以通过

$getTodayDateFormat = App\Helpers\DateHelpers::getTodayFormat();

编辑1:

根据问题描述。您需要在设置表中创建一行。

//create_settings_table.php Migration File
public function up()
    {
        // Create table for storing roles
        Schema::create('settings', function (Blueprint $table) {
            $table->increments('id');
            $table->string('app_name')->default("My App Name");
            $table->unsignedInteger('first_day_of_the_week')->default(1);
            ....
            $table->timestamps();
        });
    }

您只需要设置表的一行来检索/更新默认值。

//获取第一天

$first_day_of_the_week = App\Setting::first()->first_day_of_the_week;

//更新第一天

...
$first_day_of_the_week = request('first_day_of_the_week');
App\Setting::first()->update([
    'first_day_of_the_week' => $first_day_of_the_week
]);

推荐阅读