久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

Laravel - 從設置表中設置全局變量

Laravel - Set global variable from settings table(Laravel - 從設置表中設置全局變量)
本文介紹了Laravel - 從設置表中設置全局變量的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

我正在嘗試將 settings 表中的所有設置存儲到一個全局變量中,但我現在被卡住了(我不知道下一步是什么),這是我的實際模型和播種機:

模型 - Settings.php

class 設置擴展模型{受保護的 $table = '設置';公共 $timestamps = false;受保護的 $fillable = ['名稱','價值',];}

播種機 - SettingsTableSeeder.php

class SettingsTableSeeder 擴展 Seeder{公共函數運行(){$設置= [['姓名' =>'title', 'value' =>''],['姓名' =>'臉書', '價值' =>''],['姓名' =>'推特', '價值' =>''],['姓名' =>'instagram', '價值' =>'']];foreach($settings 作為 $setting){AppSetting::create($setting);}}}

如何將所有數據存儲在設置表中,然后可以從刀片、任何控制器或視圖訪問?

編輯

<小時>

現在,我的問題是,如何更新表單中的單個或多個值?

我已經設置了:

我的路線:

Route::put('/', ['as' => 'setting.update', 'uses' => 'AdminAdminConfiguracoesController@update']);

我的管理員AdminConfiguracoesController:

class AdminConfiguracoesController 擴展了 AdminBaseController{私人 $repository;公共函數 __construct(SettingRepository $repository){$this->repository = $repository;}公共函數geral(){返回視圖('admin.pages.admin.configuracoes.geral.index');}公共功能社交(){返回視圖('admin.pages.admin.configuracoes.social.index');}公共功能分析(){返回視圖('admin.pages.admin.configuracoes.analytics.index');}公共函數更新($id,工廠 $cache,設置 $setting){$this->repository->findByName($setting);$cache->forget('settings');返回重定向('管理員');}}

我的設置存儲庫:

class SettingRepository{私人 $model;公共函數 __construct(設置 $model){$this->model = $model;}公共函數 findByName($name){返回 $this->model->where('name', $name)->update();}}

我的刀鋒形態:

<代碼>{!!Form::model(config('settings'), ['class' =>'s-form', 'route' => ['setting.update']]) !!}{{ method_field('PUT') }}<div class="s-form-item text"><div class="item-title required">Título do artigo</div>{!!Form::text('title', null, ['placeholder' => 'Nome do site']) !!}@if($errors->has('title'))<div class="item-desc">{{ $errors->first('title') }}</div>@萬一

<div class="s-form-item s-btn-group s-btns-right"><a href="{{ url('admin') }}" class="s-btn cancel">Voltar</a><input class="s-btn" type="submit" value="Atualizar">

{!!表單::關閉() !!}

但事情并不奏效.如何將值更新到表中?

解決方案

查看更新 2 中改進的答案

我會為此添加一個專門的服務提供商.它將讀取存儲在數據庫中的所有設置并將它們添加到 Laravel 配置中.這樣,設置只有一個數據庫請求,您可以像這樣訪問所有控制器和視圖中的配置:

config('settings.facebook');

第 1 步:創建服務提供者.

您可以使用 artisan 創建服務提供者:

php artisan make:provider SettingsServiceProvider

這將創建文件 app/Providers/SettingsServiceProvider.php.

第 2 步:將其添加到您剛剛創建的提供程序的引導方法中:

/*** 引導應用程序服務.** @return 無效*/公共函數引導(){//Laravel >= 5.2,對于 Laravel <= 5.1 使用 'lists' 而不是 'pluck'config()->set('settings', AppSetting::pluck('value', 'name')->all());}

來自 Laravel 文檔:

<塊引用>

[啟動方法] 在所有其他服務提供者注冊后調用,這意味著您可以訪問框架注冊的所有其他服務.

http://laravel.com/docs/5.1/providers#the-啟動方法

第 3 步:在您的應用中注冊提供商.

將此行添加到 config/app.php 中的 providers 數組:

AppProvidersSettingsServiceProvider::class,

就是這樣.快樂編碼!

更新: 我想補充一點,引導方法支持依賴注入.因此,您可以注入存儲庫/綁定到存儲庫的接口,而不是硬編碼 AppSetting,這非常適合測試.

更新 2: 作為 Jeemusu 在他的評論中提到,該應用程序將在每次請求時查詢數據庫.為了阻止這種情況,您可以緩存設置.基本上有兩種方法可以做到這一點.

  1. 每次管理員更新時將數據放入緩存中設置.

  2. 只需記住緩存中的設置一段時間,并在管理員每次更新設置時清除緩存.

為了讓思考更具容錯性,我會使用第二個選項.緩存可能會被無意清除.只要管理員沒有設置設置或者您在服務器崩潰后重新安裝,第一個選項就會在全新安裝時失敗.

對于第二個選項,更改服務提供商啟動方法:

/*** 引導應用程序服務.** @param IlluminateContractsCacheFactory $cache* @param AppSetting $settings** @return 無效*/公共功能引導(工廠 $cache,設置 $settings){$settings = $cache->remember('settings', 60, function() use ($settings){//Laravel >= 5.2,對于 Laravel <= 5.1 使用 'lists' 而不是 'pluck'返回 $settings->pluck('value', 'name')->all();});config()->set('settings', $settings);}

現在你只需要在管理員更新設置后讓緩存忘記設置鍵:

/*** 更新設置.** @param int $id* @param IlluminateContractsCacheFactory $cache** @return IlluminateHttpRedirectResponse*/公共函數更新($id,工廠 $cache){//...//當設置更新后,清除鍵 'settings' 的緩存:$cache->forget('settings');//例如,重定向回設置索引頁面并顯示成功的提示信息return redirect()->route('admin.settings.index')->with('更新', 真);}

I'm trying to store all my settings from my settings table into a global variable, but I'm stucked now(I have no idea what's the next step), this is my actual model and seeder:

model - Settings.php

class Setting extends Model
{
    protected $table = 'settings';

    public $timestamps = false;

    protected $fillable = [
        'name',
        'value',
    ];
}

seeder - SettingsTableSeeder.php

class SettingsTableSeeder extends Seeder
{
    public function run()
    {

        $settings = [
            ['name' => 'title', 'value' => ''],
            ['name' => 'facebook', 'value' => ''],
            ['name' => 'twitter', 'value' => ''],
            ['name' => 'instagram', 'value' => '']
        ];

        foreach($settings as $setting){
            AppSetting::create($setting);
        }
    }
}

How can I store all the data inside the settings table and make then acessible from blade, or any controller or view?

Edit


Now, my question is, how can i update a single or multiple value(s) from a form?

I have set this up:

My route:

Route::put('/', ['as' => 'setting.update', 'uses' => 'AdminAdminConfiguracoesController@update']);

My AdminAdminConfiguracoesController:

class AdminConfiguracoesController extends AdminBaseController
{
    private $repository;

    public function __construct(SettingRepository $repository){
        $this->repository = $repository;
    }

    public function geral()
    {
        return view('admin.pages.admin.configuracoes.geral.index');
    }

    public function social()
    {
        return view('admin.pages.admin.configuracoes.social.index');
    }

    public function analytics()
    {
        return view('admin.pages.admin.configuracoes.analytics.index');
    }

    public function update($id, Factory $cache, Setting $setting)
    {
        $this->repository->findByName($setting);

        $cache->forget('settings');

        return redirect('admin');
    }
}

My SettingRepository:

class SettingRepository
{
    private $model;

    public function __construct(Setting $model)
    {
        $this->model = $model;
    }

    public function findByName($name){
        return $this->model->where('name', $name)->update();
    }
}

My blade form:

{!! Form::model(config('settings'), ['class' => 's-form', 'route' => ['setting.update']]) !!}
{{ method_field('PUT') }}
<div class="s-form-item text">
    <div class="item-title required">Título do artigo</div>
    {!! Form::text('title', null, ['placeholder' => 'Nome do site']) !!}
    @if($errors->has('title'))
        <div class="item-desc">{{ $errors->first('title') }}</div>
    @endif
</div>
<div class="s-form-item s-btn-group s-btns-right">
    <a href="{{ url('admin') }}" class="s-btn cancel">Voltar</a>
    <input class="s-btn" type="submit" value="Atualizar">
</div>
{!! Form::close() !!}

But things does not work. How can I update the values into the table?

解決方案

See improved answer in Update 2

I would add a dedicated Service Provider for this. It will read all your settings stored in the database and add them to Laravels config. This way there is only one database request for the settings and you can access the configuration in all controllers and views like this:

config('settings.facebook');

Step 1: Create the Service Provider.

You can create the Service Provider with artisan:

php artisan make:provider SettingsServiceProvider

This will create the file app/Providers/SettingsServiceProvider.php.

Step 2: Add this to the boot-method of the provider you have just created:

/**
 * Bootstrap the application services.
 *
 * @return void
 */
public function boot()
{
    // Laravel >= 5.2, use 'lists' instead of 'pluck' for Laravel <= 5.1
    config()->set('settings', AppSetting::pluck('value', 'name')->all());
}

From the Laravel Docs:

[The boot method] is called after all other service providers have been registered, meaning you have access to all other services that have been registered by the framework.

http://laravel.com/docs/5.1/providers#the-boot-method

Step 3: Register the provider in your App.

Add this line to the providers array in config/app.php:

AppProvidersSettingsServiceProvider::class,

And that's it. Happy coding!

Update: I want to add that the boot-method supports dependency injection. So instead of hard coding AppSetting, you could inject a repository / an interface that is bound to the repository, which is great for testing.

Update 2: As Jeemusu mentioned in his comment, the app will query the database on every request. In order to hinder that, you can cache the settings. There are basically two ways you can do that.

  1. Put the data into the cache every time the admin is updating the settings.

  2. Just remember the settings in the cache for some time and clear the cache every time the admin updates the settings.

To make thinks more fault tolerant, I'd use the second option. Caches can be cleared unintentionally. The first option will fail on fresh installations as long as the admin did not set the settings or you reinstall after a server crash.

For the second option, change the Service Providers boot-method:

/**
 * Bootstrap the application services.
 *
 * @param IlluminateContractsCacheFactory $cache
 * @param AppSetting                        $settings
 * 
 * @return void
 */
public function boot(Factory $cache, Setting $settings)
{
    $settings = $cache->remember('settings', 60, function() use ($settings)
    {
        // Laravel >= 5.2, use 'lists' instead of 'pluck' for Laravel <= 5.1
        return $settings->pluck('value', 'name')->all();
    });

    config()->set('settings', $settings);
}

Now you only have to make the cache forget the settings key after the admin updates the settings:

/**
 * Updates the settings.
 *
 * @param int                                 $id
 * @param IlluminateContractsCacheFactory $cache
 *
 * @return IlluminateHttpRedirectResponse
 */
public function update($id, Factory $cache)
{
    // ...

    // When the settings have been updated, clear the cache for the key 'settings':
    $cache->forget('settings');

    // E.g., redirect back to the settings index page with a success flash message
    return redirect()->route('admin.settings.index')
        ->with('updated', true);
}

這篇關于Laravel - 從設置表中設置全局變量的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

add new element in laravel collection object(在 Laravel 集合對象中添加新元素)
Creating an edit modal in Laravel 5(在 Laravel 5 中創建編輯模式)
Laravel 5.5 API resources for collections (standalone data)(用于集合的 Laravel 5.5 API 資源(獨立數據))
What is the best practice to create a custom helper function in php Laravel 5?(在 php Laravel 5 中創建自定義輔助函數的最佳實踐是什么?)
No #39;Access-Control-Allow-Origin#39; header - Laravel(沒有“Access-Control-Allow-Origin標頭 - Laravel)
Laravel Passport Route redirects to login page(Laravel Passport Route 重定向到登錄頁面)
主站蜘蛛池模板: 日韩精品成人 | 亚洲成人精 | 亚洲精品久久久一区二区三区 | 欧美一区二区 | 中文字幕精品一区二区三区精品 | 91资源在线 | 狠狠骚| 日本天堂视频在线观看 | 成人免费一区二区三区牛牛 | 国产精品国产馆在线真实露脸 | 蜜桃日韩 | 特级一级黄色片 | 久久久久久久久蜜桃 | 国产高清在线精品一区二区三区 | 免费日韩av | 天天干天天谢 | 久久精品| 色视频欧美 | 欧美mv日韩mv国产网站91进入 | 国产小视频在线 | 国产精品视频中文字幕 | 欧洲妇女成人淫片aaa视频 | 午夜理伦三级理论三级在线观看 | 欧美1—12sexvideos | www.日本在线观看 | 亚洲欧美日韩精品久久亚洲区 | 国产亚洲欧美在线 | 久草网址| 18gay男同69亚洲网站 | 国产美女视频一区 | 欧美精品久久 | 亚洲视频1区| 成人h动漫亚洲一区二区 | 久久亚洲一区二区 | 亚洲三级在线观看 | h视频在线免费 | 亚洲国产精品成人综合久久久 | 懂色一区二区三区免费观看 | 国产高清一区二区 | 中文字幕第100页 | 国产精品久久久久久久久久软件 |