Raj Shah
Raj Shah

Reputation: 161

How to display a flash message along with redirect without using Session in laravel?

I have a part of code which checks for the file uploaded by user. If I find that is file is not a valid png/jpg/jpeg file then I am deactivating the user and logging him out from the site and deleting his session and then redirecting him to login page. I want to display the error to him that he/she is trying to upload an invalid file. I am not able to find anything on how to display it without using Session. Any help will be appreciated.

Upvotes: 1

Views: 2971

Answers (2)

Clemen
Clemen

Reputation: 404

For example, if you don't want to use session for some reason, this is a simple code to show the error message in a specific view and then we give to the user a link to login again.

UploadController.php

public function myUpload(){

  //... some stuff and then logout the user, delete the session

  return view('uploadError', ['uploadError' => 'for some reason...']);
}

uploadError.blade.php

Error uploading the file: {{ $uploadError }}

<a href="/login">Login again</a>

In your case, you can't use the error sessions system because when you delete it, in this moment the user haven't a session, and the response has not session. And if you redirect to the login page from the controller, this login request will generate the new session, not before.

Upvotes: 1

Teoman Tıngır
Teoman Tıngır

Reputation: 2866

You can create new session messages after flush the session, these messages will delete after shown

controller

$is_valid // boolean 

if(!is_valid) {
// if file is not valid, do something
 ...
// clear all session
session()->flush()
// redirect user to login page and send session message
return redirect()->route("login")
                 ->with("message","Your file is not valid")
                 ->with("message_type","danger");

login.blade

@if(session()->has("message"))
<div class="alert alert-{{session("message_type")}}">
  <p> {{session("message")}} </p>
</div>
@endif

Upvotes: 2

Related Questions