Have you ever needed to share one variable with multiple views in Laravel? Here's a simple solution for that.
use App\Models\Post;use Illuminate\Support\Facades\View;use Illuminate\Support\Facades\Schema;use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider{ public function boot() { if (Schema::hasTable('posts')) { View::share('recentPosts', Post::latest()->take(3)->get()); } }}
Tip given by @codewithdary
Enjoyed This Tip?
Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.
Recent Courses
[NEW] Laravel 13 Starter Kit Teams and Customizations
10 lessons
33 min
Queues in Laravel 13
18 lessons
1 h 12 min read
Laravel AI SDK: 6 Practical Examples
9 lessons
1 h 02 min