You'd want to use View::share
to share data between all views. You can read more about it in the documentation under Sharing Data With All Views.
@tinkivinki I have my own partial solution, that involves using array_merge
:
In the FrontendController I have:
namespace App\Http\Controllers;
use App\Models\Settings;
class FrontendController extends Controller
{
protected $theme_directory;
protected $site_settings;
public $data;
public function __construct()
{
$this->theme_directory = Settings::first()->theme_directory ?? null;
$this->site_settings = Settings::first();
}
}
In the ArticlesController I have:
namespace App\Http\Controllers;
use App\Models\Article;
use App\Models\Settings;
class ArticlesController extends FrontendController {
public function index() {
// All articles
$articles = Article::all();
$this->data = array_merge($this->site_settings, ['articles' => $articles]);
return view('themes/' . $this->theme_directory . '/templates/index', $this->data);
}
public function show($slug) {
// Single article
$article = Article::where('slug', $slug)->first();
$this->data = array_merge($this->site_settings, ['article' => $article]);
return view('themes/' . $this->theme_directory . '/templates/single', $this->data);
}
}
There is a problem thou, I get the error;
array_merge(): Expected parameter 1 to be an array, object given
In your code $this->site_settings = Settings::first();
will result in an object of the type Settings. If you change it to $this->site_settings = Settings::first()->toArray();
you get an array.
And currently you have a duplicate call to your database:
public function __construct()
{
$this->theme_directory = Settings::first()->theme_directory ?? null;
$this->site_settings = Settings::first();
}
Every call to Settings::first()
will get the record from the database.
You can change it to something like:
public function __construct()
{
$settings = Settings::first();
$this->theme_directory = $settings->theme_directory ?? null;
$this->site_settings = $settings->toArray();
}
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community