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.