moh_abk
moh_abk

Reputation: 2164

Check if session exists inside blade template - Laravel

Currently I have the below code in one of my vanilla php files

<?php 

if (isset($_SESSION['qwick'])) {
    include "checkout-lin.php";
} else {
    include "checkout-nlin.php";
}

?>

How can I do the same in laravel. I have created 2 files in my includes folder named loggedinclude.blade.php and notloggedinclude.blade and I now want to add them in a page checkstatus.blade.php

Also I'm able to set a session like this

$vars = [
    "email" => $email,
    "password" => $password,
    "firstname" => $row['firstName'],
    "lastname" => $row['lastName'],
    "id" => $row['id']
];

session()->put('blog', $vars);

From the above code, I'm creating an array then putting the array in a session called blog thereby setting the a session called blog. and now I want to be able to check if a session named blog has been set. blog then has variable email etc

FYI;

my first question is checking for session exist in blade

my second question is checking for named session exist in controller

The documentation only has code for checking session items

if ($request->session()->has('users')) {
    //
}

Upvotes: 4

Views: 56435

Answers (4)

mohammadreza gohari
mohammadreza gohari

Reputation: 160

you can use this way for Laravel : In your Controller or Route function:

$request->session()->flash('your_session', 'your message');

and in Resource/Views/your_blade_file.blade.php

@if (session()->has('your_session'))
    anything ...
@endif

Upvotes: 5

Venkat.R
Venkat.R

Reputation: 7746

Try the below Code Snippet.

@if(session->has('qwick')) 
 @include('includes.loggedinclude checkout-lin')
@else
  @include('checkout-nlin')
@endif

Reference:

Laravel Session variables in Blade @if

http://laravel-recipes.com/recipes/90/including-a-blade-template-within-another-template

If statements in blade templating?

Upvotes: 0

Ananda G
Ananda G

Reputation: 2539

The better way to check out the user is logged inside the controller. Checking user log in in view section may be break the MVC rule. Thanks.

If you must need you can try this

@if(session->get('qwick'))
@include("includes.loggedinclude")
@else 
@include("notloggedinclude.loggedinclude")
@endif

Upvotes: -2

Erik
Erik

Reputation: 555

@if(session()->has('qwick'))
    @include('includes.loggedinclude')
@else 
    @include('notloggedinclude.loggedinclude')
@endif

Documentation about blade can be found here. Session documentation can be found here.

Upvotes: 23

Related Questions