0

I have a view called side.balde.php which is like a sidebar. This side is called in to home and various other views using @include.

If i just return view side.balde.php with variables/data in my controller, then home view can't recognize the variables.

 return view('incs/side',compact('users','etc'));

I can return this data with home view and all the @includes in home view can inherit this data. but the problem is I'm using this @include in few other pages.

how do I forward data to side.balde.php so all views calling side.balde.php can access the data.

3
  • 2
    Take a look at view composers. (Not sure if 'incs/side' works and compact('users''etc') is missing a comma) Commented Apr 16, 2020 at 9:36
  • I typed the code wrong, comma is not the problem. I don't understand the link you sent, it's too complex for me. I don't even have some of the files and folders mentioned in documentation like App\Repositories\UserRepository and app\Http\View\Composers. Can some one send a working example. Commented Apr 16, 2020 at 10:18
  • I don't want to sound rude, but you'll have a hard time developing if you can't adapt code examples to your specific needs. Sorry I can't be of more help, good luck Commented Apr 16, 2020 at 10:26

2 Answers 2

1

there are 2 options to share data across multiple views:

  1. App Service Provider (Short) Open your app service provider and in boot method write:

    $users = User::get(); View::share('users', $users); Now all of your views will have access to that key users.

  2. View Composers Please visit this link to understand how the view composer works.

You can get your work done with the first option though. Thanks.

Sign up to request clarification or add additional context in comments.

2 Comments

i tried the first methods before, thought it wouldn't work. i get this error 'Call to a member function followings() on null' . followings() is a belongsToMany relation between user and followers table declared in user.php model. Any idea how i can make followings() accessible in AppServiceProvider?
You can use with to get relations data. like User::with('following')->get();
0

got it working with

public function boot()
    {

      View::composer('*', function ($view) {
        //code
        $view->with('users', $users);
        });

    }

and at top used use App\User; and use Illuminate\Support\Facades\View;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.