Flash消息显示,有时不显示

时间:2019-04-11 22:27:29

标签: laravel vue.js flash-message

我正在使用spatie/laravel-flash来显示一些即时消息。当我使用简单的HTML表单时,它可以工作,但是当我使用Vue.js模板时,该消息不显示。 (有时他们没有),然后提交表单并转到下一个请求。

主要布局

<div class="col-lg-12 mb-2">
    @include('layouts.partials.flash_message')
</div>
<section class="py-5">
    @yield('content')
</section>

layouts.partials.flash_message

@if(flash()->message)
    <div class="{{ flash()->class }} alert-dismissible" role="alert">
        <button type="button" class="close close-white" data-dismiss="alert">×</button>
        {{ flash()->message }}
    </div>
@endif

create.blade.php

@extends('layouts.main_layout')
@section('content')   
    <create-school> </create-school>
@endsection

Vue.js模板store()方法

store()
{
    axios.post('/master/schools', {
        name: this.name,
    }.then((response) => {
        this.name = ''
    }));
}

Laravel存储方法

<?php

public function store(Request $request)
{
    $school = School::create([
        'name' => $request->name,
    ]);

    flash('success message', 'alert alert-success');

    return back();
}

1 个答案:

答案 0 :(得分:0)

由于您正在使用ajax存储数据,因此您将需要在请求中提供消息作为响应。因此,基本上,控制器上的store方法看起来像

public function store(Request $request)
{
    $school = School::create([
        'name' => $request->name,
    ]);

    return response($school, 201);
}

201是表示已创建资源的HTTP代码,通过RFC,您应该在响应中返回该资源。

在您的Vue文件中,store方法将是

store()
{
    axios.post('/master/schools', {
        name: this.name,
    }.then((response) => {
        this.name = ''
        // Modify your DOM or alert the user
        alert('Resource created')
    }));
}

作为建议,您应该在存储之前取消验证用户输入。

相关问题