How to get id from Auth::user() ?

Published 1 week ago by wardaddy

I want to display the data from the channel where "user_id" in the channel table is the same as the "id" of 'Auth::user()'

Users Table

id | name | email | password |

| --- | --- | --- | --- |

| 1 | john | [email protected] | 123 |

| 2 | jane | [email protected] | 321 |

Channels Table

| id | user_id | name |

| --- | --- | --- |

| 1 | 1 | Channel #1 |

| 2 | 2 | Channel #2 |

this is what i need

if user selects "Manage Channel" menu, the menu will display information from his own channel

dashboard.blade.php

<a href="{{ url('/dash/manage-channel') }}" class="waves-effect"><i class="material-icons left">view_list</i>Manage Channel</a>

here my code

channelController.php

use Auth; //has been added at the top


public function edit(channel $channel)
{
     $channels = Channel::where('user_id', '=', Auth::user()->id); //trying to get id from Auth::user()
     return view('dashboard.manageChannel', compact('channels'));
}
Best Answer (As Selected By wardaddy)
zachleigh

You arent actually getting the records. You're only getting a builder instance. You need to call get.

$channels = Channel::where('user_id', '=', Auth::user()->id)->get();
zachleigh
zachleigh
1 week ago (200,130 XP)

What happens when you run the above code?

wardaddy

@zachleigh the code leads me to 'dashboard.channel', but does not display the information from the channel as I expected

here my code in manageChannel.blade.php

@foreach ($channels as $channel)
       <form method="POST" action="/channels/{id}/edit" class="file-field input-field">
        {{ csrf_field() }}
        {{ method_field('PUT') }}
        <button type="submit" class="btn">submit</button>
        <div class="file-path-wrapper">
            <input type="text" name="channel_name" id="channel_name" value="{{ $channel->name }}" class="validate">
            <label for="channel_name" class="light">Rename Channel</label>
        </div>
    </form>
@endforeach
zachleigh
zachleigh
1 week ago (200,130 XP)

You arent actually getting the records. You're only getting a builder instance. You need to call get.

$channels = Channel::where('user_id', '=', Auth::user()->id)->get();
Snapey
Snapey
1 week ago (647,375 XP)

why don't you have a channel relationship on the User model?

then;

$channels = request()->user->channels()->get();
wardaddy

@Snapey I have tried your suggestion and there it appears FatalErrorException

Call to a member function channels() on null

wardaddy

@zachleigh thanks a lot, your code works well and is easy to understand

Please sign in or create an account to participate in this conversation.