Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Thirdwrist's avatar

Please my session keeps entering false and not true

I built this logic to help me count my views on one page, but the logic keeps going bck to false and incrementing the results even after the session is registered. Am i making any mistakes?

    public function handle( $request, Closure $next)
    {
        $id = $request->route('id');
        if($request->session()->exists($id))
        {
            dd( $id. " i am still alive bro");
             return $next($request);
             
        }

        else
        {
            dd( $id. " i am still dead bro");
            session([$id =>"some value"]);
            $value = session($id);
            echo $value;
            $results = DB::select('select page_views from posts where id = ?', [$id]);
            $results= $results[0]->page_views;
            $results++;      
            DB::table('posts')
                ->where('id', $id)
                ->update(['page_views' => $results]);        
            return $next($request);
        }
        
    }
0 likes
3 replies
jlrdw's avatar

Try an echo, dd means die there and dump.

Thirdwrist's avatar

@jlrdw Thats exctly what I want it to do, just to test the code. When its starts working then I can remove the DD();

Thirdwrist's avatar
Thirdwrist
OP
Best Answer
Level 1

Just for who ever might run into this same error :

apparently the problem was that you can't initialize a session in the middleware, I had to create a function in my post model that initialized the session in the model if the request comes back false. here are the codes.

<?php

namespace App\Http\Middleware;
use App\Post as post;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class viewcount
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle( $request, Closure $next)
    {
        $id = $request->route('id');
        $session_id = "twenty" . $id;
        
        
        

        if(Session()->exists($session_id))
        {
            return $next($request);    
        }


        else{
            
            $var = new post;
            $var->viewcount_session($session_id);
            $results = post::select('page_views')->find($id);
            $results= ++$results->page_views;
            $results= DB::table('posts')->where('id', $id)->update(['page_views' => $results]);

            return $next($request);
        }
        
    }
}
 ?>

this is the model method below

public function viewcount_session($session_id){
        $var = $session_id;
        return  $value = session([$var =>'car']);
        redirect('/articles/{id}');

Please or to participate in this conversation.