Summer Sale! All accounts are 50% off this week.

MahmoudAdelAli's avatar

Is good to use flat map with controller to manage cms phrases?

After my last question about using config and cache i found the cache is better , now i using this way to manage the cms phrases after store settings at data base with seeder and cache it

# home controller
 public function index() {
        $data = collect(Cache::get('settings')->where('language','en'))
            -> flatMap(function ($data){
            return [$data['option'] => $data['value'],];
        });

        return view('clientside.Home.home',[
            'data' => $data,
            'courses' => Course::whereStatus('1')->limit(6)->get(),
            'products' => Product::whereStatus('1')->limit(3)->get(),
            'teachers' => Teacher::whereStatus('1')->limit(3)->get(),
        ]);
    }

and at the blade i get it like that

{{dd($data['logo-link'])}}

is that clean code and correct way , or there's better than ?

0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

The use of flatMap in the controller to manage CMS phrases is a valid approach. It allows for easy retrieval of data from the cache and mapping it to a collection. However, it is important to ensure that the data being cached is up-to-date and that the cache is cleared when necessary. Additionally, it may be beneficial to abstract the caching logic into a separate class or service to improve code organization and maintainability.

Here is an example of how the caching logic could be abstracted into a separate service:

// CmsService.php

namespace App\Services;

use Illuminate\Support\Facades\Cache;

class CmsService
{
    public function getPhrases($language)
    {
        return collect(Cache::get('settings')->where('language', $language))
            ->flatMap(function ($data) {
                return [$data['option'] => $data['value']];
            });
    }
}

Then, in the controller, the service can be used to retrieve the CMS phrases:

// HomeController.php

namespace App\Http\Controllers;

use App\Services\CmsService;
use App\Models\Course;
use App\Models\Product;
use App\Models\Teacher;

class HomeController extends Controller
{
    protected $cmsService;

    public function __construct(CmsService $cmsService)
    {
        $this->cmsService = $cmsService;
    }

    public function index()
    {
        $data = $this->cmsService->getPhrases('en');

        return view('clientside.Home.home', [
            'data' => $data,
            'courses' => Course::whereStatus('1')->limit(6)->get(),
            'products' => Product::whereStatus('1')->limit(3)->get(),
            'teachers' => Teacher::whereStatus('1')->limit(3)->get(),
        ]);
    }
}

This approach separates the caching logic from the controller and makes it easier to test and maintain.

1 like

Please or to participate in this conversation.