How to Get the logged in User ID in Laravel 5.2 - php

In my application I used the scaffolding method for creating authentication fast. But I just got one problem while playing with it. Actually I can get Auth::user()->name current logged in user username and other details but I can't get the user ID , I tried to get the ID with Auth::user()->id and Auth::id() but all in vain. Is there any method to get the current logged in user ID ?
What I tried :
I created a variable in AuthServiceProvider and then tried to get the ID in view like this
ServiceProvider
$id = Auth::id();
view()->share('id', $id);
View
> <li><a href="{{ url('/users/{!! $id !!}') }}"><i class="fa fa-btn
> fa-sign-out"></i>Profile</a></li>
Next Try in View:
<li><i class="fa fa-btn fa-sign-out"></i>Profile</li>
I want to get the logged in user ID so that I can show every user his/her profile.

You're doing a {!! !!} echo inside a {{ }}, but you can't nest those. It's like having <?php echo <?php echo ... ?> ?>. The nested printing is also inside quotes. Assuming that your idvariable is correctly set, here's how the call should look:
<a href="{{ url('/users/' . $id) }}">
Much easier too read, right? :)

in View try this:
{{ Auth::user()->name }}
in Controller try this:
\Auth::user()->id;

Related

How can other users view a user's profile details in octobercms?

Displaying a user's information to the user is pretty much straight forward using their id or name in the url as parameter and displaying specific details using {{ user.name }}, {{ user.phone }} etc. But how can i display a specific user info to other users. When i click on www.example.com/profile/joe, it takes me to joe's profile. Trying it logged out or from a different account throws up an error.
This what i have done so far. my profile url has
url = "/:id"
and my php block
[session]
==
<?php function onStart(){
$profile = $this->param('id');
}
?>
==
this links up to the profile page
<button style="font-family: arial" class="btn btn-sm btn-light rounded--lg-pill shadow rounded border col-6">View Profile</button>
using {{ user.name }}, {{ user.phone }} etc shows all the logged in user's info. I am just at lost here how to make the profile of a user available to other users.
Edit:
Currently working if i use $userProfile = Auth::findUserById($profile)
connected to <a href = ''{{ id: users.id }}''>View Profile></a>
It still works if I change it to
$userProfile = Auth::findUserByLogin($profile)
connected to
<a href = ''{{ id: users.username }}''>View Profile></a>
or
<a href = ''{{ id: users.email }}''>View Profile></a>
but i would have loved it to work using a different field
<a href = ''{{ id: user.company_name }}''>View Profile></a> instead of id or login details
Suppose we are generating link : www.example.com/profile/joe
so id will be joe now we need to find that user's record and use it
to find it in code
[session]
==
<?php function onStart(){
$profile = $this->param('id');
$this['userProfile'] = Auth::findUserByLogin($profile);
// you can use other field if you need
// $this['userProfile'] = \RainLab\User\Models\User::where('username', $profile)->first();
}
?>
==
use it in template
{{ userProfile.name }}, {{ userProfile.phone }}
if any doubts please add comment.

How can I get id from url with Request $request? (Laravel 5.3)

My link href on the view is like this :
<a href="{{ route('message.inbox.detail.id', ['id' => $message->id]) }}" class="btn btn-default">
<span class="fa fa-eye"></span> {{ trans('button.view') }}
</a>
My routes is like this :
Route::get('message/inbox/detail/id/{id}', ['as'=>'message.inbox.detail.id','uses'=>'MessageController#detail']);
When clicked, the url display like this :
http://myshop.dev/message/inbox/detail/id/58cadfba607a1d2ac4000254
I want get id with Request $request
On the controller, I try like this :
public function detail(Request $request)
{
dd($request->input('id'));
}
The result : null
How can I solve it?
You can get it like this
$request->route('id')
Inside request class you can access it this way
$this->route('id')
I usually use it when I'm validating field to make sure it's unique, and I need to exclude model by ID when I'm doing update
This is because you're passing the id parameter through url, you should send it using a form like this
{!! Form::open(['route'=>' route('message.inbox.detail.id', 'method'=> 'POST']) !!}
<input type="hidden" name="id" value="{{ $message->id }}" />
{!! Form::submit({{ trans('button.view') }}, ['class'=>'btn btn-default']) !!}
{!! Form::close() !!}
and now you can access via request in your controller
public function detail(Request $request)
{
dd($request->input('id'));
}
For people who are looking for answers using newer versions of laravel, you can get the route id using the following:
Example route with model binding
Route::put('/post/{post}, [PostController::class, 'update]);
$this->route('id') will not work in this case due to model binding.
instead you can do this:
// using in controller
request()->route('post.id);
or
// using in form request
$this->route('post.id');
Get the id via this:
public function detail($id)
{
dd($id);
}

Laravel-5.3 : Updating session not working properly

I'm using database driver to store sessions. When I update the payload, the views, wich depend on the datas into the payload, don't update.
Into my view, I often have things like that:
#if( Session::get('quicktrade') == 'Client' )
<li class="#if ($coreData['navParent'] == 'quicktrade') active open #endif">
<a href="javascript:;">
<i class="ico-quicktrade-{{Session::get('left_menu')}}"></i>
<span class="title">QUICK[TRADE]</span>
<span class="arrow #if ($coreData['navParent'] == 'quicktrade') open #endif"></span>
#if ($coreData['navParent'] == 'quicktrade') <span class="selected"></span> #endif
</a>
<ul class="sub-menu">
#if( Session::get('quicktrade_evaluation') == 1 )
<li class="#if ($coreData['navChild'] == 'evaluation') active #endif">
<a href="{{ url('/quicktrade/evaluation') }}">
NOUVELLE ÉVALUATION</a>
</li>
#endif
#if ( Session::get('quicktrade_liste') == 1 )
<li class="#if ($coreData['navChild'] == 'liste') active #endif">
<a href="{{ url('/quicktrade/liste') }}">
LISTE DES VÉHICULES</a>
</li>
#endif
#if ( Session::get('quicktrade_statistiques') == 1 )
<li class="#if ($coreData['navChild'] == 'statistiques') active #endif">
<a href="{{ url('/quicktrade/statistiques') }}">
STATISTIQUES</a>
</li>
#endif
</ul>
</li>
#endif
This make the menu to show or not options depend on the session.
All the datas are added to the payload during the LogSuccesfulLogin event.
So, if the user logout then login, I got no problem when I do some changes in the users table.
The problem is when the session is active and the user don't logout. If I do some changes, the view will stay the same as before.
In my user controller there is what happen:
$user = User::with('acces')->find($user->id);
$sessions = DB::table('sessions')->where('user_id', $user->id)->get();
foreach ($sessions as $session) {
$payload = unserialize(base64_decode($session->payload));
$payload['oneaction'] = $user->acces->oneaction;
$payload['oneaction_type'] = $user->acces->oneaction_type;
if ($user->acces->oneaction == 'Client') {
$payload['oneaction_clients'] = $user->acces->oneaction_clients;
$payload['oneaction_list'] = $user->acces->oneaction_list;
$payload['oneaction_creator'] = $user->acces->oneaction_creator;
} else {
$payload['oneaction_clients'] = 0;
$payload['oneaction_list'] = 0;
$payload['oneaction_creator'] = 0;
}
//dd($payload);
$payload = base64_encode(serialize($payload));
DB::table('sessions')->where('id', $session->id)->update(['payload' => $payload]);
}
$sessions = DB::table('sessions')->where('user_id', $user->id)->get();
foreach ($sessions as $session) {
$payload = unserialize(base64_decode($session->payload));
//dd($payload);
}
As you can see in the code above, there is 2 dd(). Both show me that the changes are done properly. When I reload the page, ther is no change in the left menu.
I tried to do a php artisan view:clear right after the sessions have been updated, but the problem persist.
The only way I'm able to make this work, it's to delete all sessions of the user into the table. I don't want to go this way, so what am I missing? Why updating session don't work as I expect?
Your session gets probably lost because your response does not contain the session-cookie. In laravel this is done via the AddQueuedCookiesToResponse middlware which is kicked off in your HTTP-Kernel. But since you are dump and dying somewhere in your controller, you are preventing this middlware from running.
Please note that this is just a guess, there could be other reasons why your cookie is getting lost. Check your kernel and maybe also your config and ensure that you can see your cookie in your http response header.

laravel send data to view via route and display it in view without altering url

on signup i am checking the invitation code the user uses using:
$match_code = DB::table('codes')->where('code', $code)->pluck('code');
if($code == $match_code){
$ip->save();
$user->save();
Auth::login($user);
return redirect()->route('news');
}else{
return redirect()->route('home')->with('message','Invalid Invite Code');
}
i tried adding this in my view :
#if(isset($message))
<li>{{ $message }}</li>
#endif
but this does not display anything, i am new to laravel. i know this is basics but i have been googling for over 45 mins with no results
The data you have send using with() is available in session, check this:
return redirect('dashboard')->with('status', 'Profile updated!');
After the user is redirected, you may display the flashed message from the session. For example, using Blade syntax:
#if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
#endif
Reference

Get the value of REDIRECT using WITH in laravel

we are trying to get the value sent with the redirect method in blade template in laravel.
Here is how my return statement looks like:
public function movetotrash($id){
$page = Pages::where('id', $id) -> first();
$page -> active = 0;
//$page -> save();
//return redirect()->route('pages.index')->with('trash','Page Moved To Trash');
return redirect('pages')->with('trash','Page Moved To Trash');
}
Now once its redirect to pages it creates are URL like this http://localhost:8888/laravelCRM/public/pages.
Then i want to print the message to user that "Page is moved to trash" with $trash variable. For which i used this :
#if(isset($trash) ))
<div class="alert alert-error">
{{ $trash }}<br><br>
</div>
#endif
What should i do to print the value?
Thank you! (in advance)
The with method flashes data to the session which is only accessible in the next request.
So you can retrieve it from the session like this:
#if(session()->has('trash'))
<div class="alert alert-error">
{{ session()->get('trash') }}
</div>
#endif
In redirect with value pass as session flash,so you need to check value like that
#if(session()->has('trash'))
then you can show like this
{{ session('trash') }}
You can send data from controller like this,
You have to assign the message into variable
$trash = Page Moved To Trash';
return redirect('pages')->with('trash');
and then in view,
use like this.
#if(session($trash) ))
<div class="alert alert-error">
{{ session($trash) }}<br><br>
</div>
#endif
The data will store in session and we can use it on redirect page
Hope this will help :)

Categories