Laravel 5.4以不同方式显示闪存错误和成功消息

l7mqbcuq  于 2023-02-25  发布在  其他
关注(0)|答案(4)|浏览(161)

PostController中的方法

public function store(PostRequest $request)
    {
        if (Post::create($request->all())) {
            $request->session()->flash('status', 'Post was successfully added!');
        } else {
            $request->session()->flash('status', 'Error!');
        }
        return redirect('/');
    }

索引视图

<?php if(session()->has('status')){
        echo '<div style="text-align: center">';
        echo session()->get('status');
        echo '</div>';
    }?>

如何以不同的方式显示错误和成功消息?

jqjz2hbq

jqjz2hbq1#

您可以使用类似于以下内容的内容:

public function store(PostRequest $request) {
    if (Post::create($request->all())) {
        $request->session()->flash('message.level', 'success');
        $request->session()->flash('message.content', 'Post was successfully added!');
    } else {
        $request->session()->flash('message.level', 'danger');
        $request->session()->flash('message.content', 'Error!');
    }
    return redirect('/');
}

在刀片文件中:

@if(session()->has('message.level'))
    <div class="alert alert-{{ session('message.level') }}"> 
    {!! session('message.content') !!}
    </div>
@endif

上面的代码使用bootstrap's alert css classes进行样式设置,其灵感来自Jeffrey Way's Laracasts Flash package

rryofs0p

rryofs0p2#

您可以通过以下方式显示即时消息:
在控制器中:

$request->session()->flash('success', 'Record successfully added!');
//OR
$request->session()->flash('warning', 'Record not added!');

在您看来:

@foreach (['danger', 'warning', 'success', 'info'] as $key)
 @if(Session::has($key))
     <p class="alert alert-{{ $key }}">{{ Session::get($key) }}</p>
 @endif
@endforeach
w46czmvw

w46czmvw3#

1.在控制器中编写如下代码:

use Illuminate\Support\Facades\Session;
    
Session::flash('error', 'Some thing is wrong. Please try again');
Redirect::to(path to blade file route);

1.在您的Blade模板中编写如下代码:

@if(Session::has('error'))
        <p class="alert alert-danger">{{ Session::get('error') }}</p>
@endif
kcrjzv8t

kcrjzv8t4#

您可以在控制器中使用->with()

public function store(PostRequest $request) {
    if (!Post::create($request->all())) {
        return redirect('/')->with('error', 'Error!');
    }

    return redirect('/')->with('success', 'Post was successfully added!');
}

您的视图可能如下所示:

@if (session('success'))
    <div class="alert alert-success">
        {{ session('success') }}
    </div>
@endif
@if (session('error'))
    <div class="alert alert-danger">
        {{ session('error') }}
    </div>
@endif

或(alert-error类使用附加CSS):

@foreach (['error', 'success'] as $status)
    @if(Session::has($status))
        <p class="alert alert-{{$status}}">{{ Session::get($status) }}</p>
    @endif
@endforeach

相关问题