Laravel-5.3 : Updating session not working properly - php

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.

Related

When a Parent has no child in a one to many relationship I get a non-object error when checking it

I have a 'Parent' Table (server) and a 'Child' Table (Server Status) the server status is connected to the server table via its id e.g. the servers id is the same as the server_id in the server status migration using a one to many relationship. What I am trying to do then is iterate through my list of servers and then display the status of the server, which is stores in the server status table. For some reason I am getting non-object error when trying to iterate through a server that has no status. This works then a server has a status that is corresponding to it but but not when I have only a server and no status. Can anyone give me some insight on to why this may be happening? Here is the current code for the controller calling this view, and the loop used to iterate through the data.
index.blade.php:
#guest
#if(count($servers) > 0)
#foreach($servers as $server)
#if($server->isPublic === 1 )
#include('inc.statuses')
#endif
#endforeach
#endif
#endguest
#auth
#if(count($servers) > 0)
#foreach($servers as $server)
#include('inc.statuses')
#endforeach
#endif
#endauth
statuses.blade.php:
#if($server->serverStatus->last()->status_id === 1)
{{$server->name}}
#elseif($server->serverStatus->last()->status_id === 2)
<a href="/servers/{{$server->id}}" class="text-dark list-group-item list-group-item-warning" >{{$server->name}}</a>
#elseif($server->serverStatus->last()->status_id === 3)
<a href="/servers/{{$server->id}}" class="text-dark list-group-item list-group-item-danger" >{{$server->name}}</a>
#elseif($server->serverStatus->last()->status_id === 4)
<a href="/servers/{{$server->id}}" class="text-dark list-group-item list-group-item-warning" >{{$server->name}} is under maintinance</a>
#elseif($server->serverStatus->last()->status_id === null)
<a href="/servers/{{$server->id}}" class="text-dark list-group-item list-group-item-warning" >{{$server->name}} has no inputted staus</a>
#else
<a href="/servers/{{$server->id}}" class="text-dark list-group-item list-group-item-warning" >{{$server->name}} has no inputted staus</a>
#endif
controller:
public function index(){
$servers = Server::orderBY('created_at', 'desc')->get();
// foreach($servers as $server){
// var_dump($server->name);
// var_dump($server->serverStatus->last()->status_id);
// var_dump($server->serverStatus->last()->server_id);
// }
$incidents = Incident::orderBY('created_at', 'desc')->paginate(10);
return view('pages.index', ['incidents' => $incidents, 'servers' => $servers]);
}
Use $servers = Server::has('serverStatus')->orderBY('created_at', 'desc')->get(); to get only servers with status.

Laravel 5 next and previous paging

Hello I have a list of max 5 articles in my homepage but I have many more articles and I would like to show these articles in other pages. So when I see more old posts, I would like to do a pagination like user home page / 1 when I get it as a result of posting it as url. But I do not follow the correct paths when I make directions.
I need to change the following lines of code to help you change the point, good day, good day
app/Http/Controller/HomeController:
public function deneme($page){
$url = url()->full();
$myUrl = explode('/', $url);
$uz= sizeof($myUrl);
$myUrl = $myUrl[$uz-1];
if ($myUrl == 'work.com'){
$yazilar = YaziModel::join('users as u','u.id','=', 'yazilar.kullaniciid')->select('yazilar.*','u.name','u.created_at')->orderBy('yazilar.id', 'DESC')->get();
$posts = array_slice($yazilar->getIterator()->getArrayCopy(),0,5);
return view('backend.pages.anasayfa')->with('yazilar', $posts);
}else{
$baslangic = $page*5;
$yazilar = YaziModel::join('users as u','u.id','=', 'yazilar.kullaniciid')->select('yazilar.*','u.name','u.created_at')->orderBy('yazilar.id', 'DESC')->get();
$posts = array_slice($yazilar->getIterator()->getArrayCopy(),$baslangic,5);
return view('backend.pages.anasayfa')->with('yazilar' ,$posts);
}
}
routes/web.php:
Route::get('/{page}', 'HomeController#deneme');
View :
<ul class="pager">
<li class="next">
Older Post →
</li>
</ul>
You can use this code in the blade (Laravel 5.7)
#if($news->previousPageUrl() != null)
<i class="fa fa-chevron-left"></i> NEWER
#endif
#if($news->nextPageUrl() != null)
OLDER <i class="fa fa-chevron-right"></i>
#endif
Use Pagination
Controller
$users = DB::table('users')->paginate(15);
View
{{ $users->links() }}
for More Details https://laravel.com/docs/5.2/pagination

How to Get the logged in User ID in Laravel 5.2

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;

Laravel get current route

I have some navigation links and I want to get the current route in laravel 5 so that I can use the class active in my navigations. Here are the sample links:
<li class="active"> Home </li>
<li> Contact </li>
<li> About </li>
As you can see, in the Home link there is the active class which means that it is the current selected route. But since I am using laravel blade so that I would not repeat every navigation links in my blades, I can't use the active class because I only have the navigation links in my template.blade.php. How can I possibly get the current route and check if it is equal to the current link? Thank you in advance.
$uri = Request::path()
Check out the docs
You can use named routes like
Route::get('/', ['as'=>'home', 'uses'=>'PagesController#index']);
and then in the view you can do the following
<li {!! (Route::is('home') ? 'class="active"' : '') !!}>
{!! link_to_route('home', 'Home') !!}
</li>
So I got it working with some little tricks. For example the url in the address bar is http://localhost:8000/tourism/places.
If I will use the Request::path() method, I will get tourism/places. But what I wanted to get is the tourism part only so what I did is this:
$currentPath = Request::path();
$values = explode("/", $currentPath);
$final = $values[0];
Now the $final variable will have the value "tourism".
Now to make the variable load globally, I included the code in the AppServiceProvider.php inside the public function boot().
public function boot()
{
$currentPath = Request::path();
$values = explode("/", $currentPath);
$final = $values[0];
view()->share('final', $final);
}
And lastly in my blade template,
<li #if ($final== "tourism") class="active" #endif>
Places
</li>
Simple way is always better, just use the same function you use to generate links and it will give you all, including the flexibility to use wild cards
<a class="nav-link {{ Request::url() === route("products.list", [$group_key]) ? 'active' : '' }}"
href="{{ route("products.list", [$group_key]) }}"
>
LInk text
</a>
Plus, you still are going to have only one place to manage URL-s - your router files.

Laravel: Making links invisible to guests

I am using L3 to make a site such that guests can leave comments without need to log in then there will be an admin login. I have a menu bar used for navigation by both the guests and admin but on admin login, the menu bar should have more options. On my layout, this is what i have;
<div class="nav-collapse collapse" id="main-menu">
<ul class="nav" id="main-menu-left">
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">Contact Us<b class="caret"></b></a>
<ul class="dropdown-menu" id="swatch-menu">
<li>{{HTML::link('posts/contact','Leave a coment')}}</li>
<li>{{HTML::link('posts/location','Grt Our Locations')}}</li>
#if (Session::has('permission'))
<li>{{HTML::link('posts/review','Review Posts')}}</li>
<li>{{HTML::link('posts/list','List all Posts')}}</li>
#endif
</ul>
</div>
On my admin controller, i created a Session so as to make posts/review and posts/list accessible to admin only. This is what i have
public function post_login()
{
$email = Input::get('email');
$password = Input::get('password');
$credentials = array
('username' => $email,
'password' => $password);
if (Auth::attempt($credentials))
{
Session::put('permission', 'admin');
return Redirect::to('admin/index');
} else
{
Session::flash('status_error', 'Your email or password is invalid - please try again.');
return Redirect::to('admin/login');
}
}
This is working OK except for the fact that Guests can see the admin links when they hover their mouse over the menu bar (i.e they can see 'Review Posts' and 'List all Post'. They cannot access the pages though (they are redirected to admin login page). My question is, how do i make these links invisible to guests but visible to admin on login? Both guest and admin have to use same layout. Thankyou in advance.
You should use the following approach instead of Session:
#if (Auth::user())
Admin
#endif
It seems like you have already signed in once and then sign out again to test the site. It looks like you didn't clear the "permission" session on sign out.

Categories