简体   繁体   中英

Pass the data in the many to many relation ship in laravel

I have create a form that will show the user the event title, event description. And the code

public function show($id){

            $showevents = Events::findOrFail($id);
            return view('events.show',compact('showevents'));
    }

This data i pass dont have the user data, but it will give me the specific event data. My question is how to pass the user data along with this? Because my event table dont have the user information, it all in the user table. I try {{$showevents->user->name}} in the view form, but it doesnt give me the information of the user.

You will be needing the user-id too if you want to retrieve infomation about the user and send it to the view file..

One thing you can do for getting the user-id anywhere is setting the user-id in Session variable when the user logs-in as:

\Session::set('user_id',$userID);

Then you can get the user-id anywhere in any controller using

$id = \Session::get('user_id');

For example in your case

public function show($id){
        $user_id = \Session::get('user_id');
        $user = User::findOrFail($user_id);

        $showevents = Events::findOrFail($id);
        return view('events.show',compact('showevents','user));
}

Now where you will set the Session variable depends entirely upon your code..I used to set after a user has logged in successfully and also rembember to remove session data when logging out as..

\Session::flush();

First of all {{$showevents->user->name}} of course will fail because you don't have any connection between events and user.

If you want to make connection between it you going to need user_id inside event table.

If you want to get user data but don't have any connection, you need to do in seperate query.

$user = User::findOrFail($user_id);

return view('events.show',compact('showevents', 'user'));

You should use Eloquent's relationship functions or wrap them inside you Models relationship functions and use them. check the Laravel documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM