Support the ongoing development of Laravel.io →
Blade Laravel.io
Last updated by @ajax30 2 years ago.
0

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.

0

@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

How do I fix this particular problem?

0
moderator

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();
    }
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Razvan ajax30 Joined 2 Oct 2021

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.