سؤال

My application is a simple CRUD application. I have a delete controller action which redirects back to the list when the item is successfully deleted. What I'm trying to add now is a message to the user that the data was successfully deleted.

My Controller Action:

public function deleteItem($id)
{
    try {
        $item = Item::findOrFail($id);
        $item->delete();
        return Redirect::to('list')->with('message', 'Successfully deleted');
    } catch (ModelNotFoundException $e) {
        return View::make('errors.missing');
    }
}

The part of my list.blade.php view where I try to display the message:

@if (isset($message))
    <div class="alert alert-success alert-dismissable">
        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
        {{ $message }}
    </div>
@endif

The problem that I have is that the $message variable is always empty ..

هل كانت مفيدة؟

المحلول

Since the with method flashes data to the session, you may retrieve the data using the typical Session::get method.

So you have to get as

$message = Session::get('message');

نصائح أخرى

You can use this on your blade template:

@if( Session::has('message') )
    <div class="alert alert-success alert-dismissable">
        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
        {{ Session::get('message') }}
    </div>
@endif

Reference: easylaravelblog

You can check APP/kernel.php and look for this:

\Illuminate\Session\Middleware\StartSession::class,

Check if it is defined more than once like in this example:

protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Session\Middleware\StartSession::class,
];

protected $middlewareGroups = [
'web' => [
    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \App\Http\Middleware\VerifyCsrfToken::class,
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],

You can comment any one of the two or delete it. We need to define it one time only.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top