Saturday, November 16, 2024
Google search engine
HomeLanguagesLaravel 9 Vue JS Flash Messages Example

Laravel 9 Vue JS Flash Messages Example

To show flash message with vue js in laravel 9 app. In this tutorial, we will learn how to display a flash messages with vue js components in laravel apps.

Many times, we submit a send or submit the form using Vue js. Then, we need to display a flash message likeĀ alert, notification, or flash message with Vue js in laravel.Ā 

The vue js flash message in laravel looks like:

laravel flash message
laravel flash message

Laravel 9 Vue JS Flash Messages Example

Follow the following steps to implement flash messages in laravel vue js apps:

  • Step 1: Install Laravel 9 App
  • Step 2: Connecting App to Database
  • Step 3: Create Model And Migration
  • Step 4: NPM Configuration
  • Step 5: Add Routes
  • Step 6: Create Controller By Command
  • Step 7: Create Vue Component
  • Step 8: Register Vue App
  • Step 9: Run Development Server

Step 1: Install Laravel 9 App

In this step, we need to install laravel latest application setup, So open terminal OR command prompt and execute the following command:

 composer create-project --prefer-dist laravel/laravel blog 

Step 2: Connecting App to Database

After successfully install laravel new application, Go to project root directory and open .env file. Then set up database credential in .env file as follow:

 DB_CONNECTION=mysql 
 DB_HOST=127.0.0.1 
 DB_PORT=3306 
 DB_DATABASE=here database name here
 DB_USERNAME=here database username here
 DB_PASSWORD=here database password here

Step 3: Create Model And Migration

Next step, open terminal and execute the following command:

php artisan make:model Post -m

This command will create one model name post.php and also create one migration file for the posts table.

Now open create_postss_table.php migration file fromĀ database>migrationsĀ and replaceĀ up()Ā function with following code:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

Next, migrate the table using the below command:

php artisan migrate

Step 4: NPM Configuration

We need to setup Vue and install Vue dependencies using NPM. So execute the following command on command prompt:

php artisan preset vue

Install all Vue dependencies:

npm install

Step 5: Add Routes

Next step, go to routes folder and open web.php file and add the following routes into file:

routes/web.php

use App\Http\Controllers\PostController;

Route::get('post', function () {
    return view('post');
});
Route::post('store', [PostController::class, 'store']);

Step 6: Create Controller By Command

Next step, open command prompt and execute the following command to create a controller by an artisan:

php artisan make:controller PostController

After that, go toĀ app\Http\ControllersĀ and open PostController.php file. Then update the following code into PostController.php file:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

Use App\Models\Post;

class PostController extends Controller

{
   
    public function store(Request $request)
    {
        $insert['title'] = $request->get('title');
        $insert['description'] = $request->get('description');
        $check = Post::insertGetId($insert);

        return response()->json($check);
    }
}

Step 7: Create Vue Component

Next step, go toĀ resources/assets/js/componentsĀ folder and create a file calledĀ Post.vue.

And update the following code into Post.vue components file:

<template> 
    <div class="container"> 
        <div class="row justify-content-center"> 
  
            <div class="col-md-8"> 
                <div class="card"> 
                    <div class="card-header"> Laravel Vue js Flash Message Example </div> 
    
                    <div class="card-body"> 
                        <form @submit="formStore"> 
                        <strong> Title:</strong> 
                        <input type="text" class="form-control" v-model="title"> 
                        <strong> Description:</strong> 
                        <textarea class="form-control" v-model="description"> </textarea> 
   
                        <button class="btn btn-success"> Submit</button> 
                        </form> 
                        <strong> Output:</strong> 
                        <pre> 
                        {{output}}
                        </pre> 
                    </div> 
                </div> 
            </div> 
        </div> 
    </div> 
</template> 
   
<script> 
    export default {
        mounted() {
            console.log('Component mounted.')
        },
        data() {
            return {
              title: '',
              description: '',
              output: ''
            };
        },
        methods: {
            formStore(e) {
                e.preventDefault();
                let currentObj = this;
                axios.post('/store', {
                    title: this.title,
                    description: this.description
                })
                .then(function (response) {
                    currentObj.output = response.data;
                    flash('Post Created Successfully', 'success');
                })
                .catch(function (error) {
                    currentObj.output = error;
                });
            }
        }
    }
</script> 

Next, create a new components named flash.vue and update the following code into flash.vue file:

<template>
    <div class="alert alert-success spacing" role="alert" v-show="show">
        {{ body }}
    </div>
</template>
   
<script>
    export default {
        props: ['message'],
        data() {
            return {
                show : false,
                body : ''
            }
        },
        created() {
            if(this.message) {
                this.flash(this.message)
            }
            window.events.$on('flash',(message) => this.flash(message))
        },
        methods: {
            flash(message) {
                this.show = true
                this.body = message
  
                setTimeout(() => {
                    this.hide()
                },3000)
            },
            hide() {
                this.show = false
            }
        }
    }
</script>
   
<style>
    .spacing {
        position: fixed;
        right: 25px;
        bottom: 25px;
    }
</style>

Now openĀ resources/assets/js/app.jsĀ and include theĀ Post.vue and Flash.vueĀ component as follow:

require('./bootstrap');
  
window.Vue = require('vue');
  
window.events = new Vue();
  
window.flash = function(message) {
    window.events.$emit('flash',message);
}
   
Vue.component('post-component', require('./components/Post.vue'));
Vue.component('flash', require('./components/Flash.vue'));
   
const app = new Vue({
    el: '#app'
});

Step 8: Register Vue App

In this step, we need to create a blade view file to define Vueā€™s app. Go toĀ resources/viewsĀ folder and make a file namedĀ post.blade.php. Then update the below code into post.blade.php file:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="csrf-token" content="{{ csrf_token() }}">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
   
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Laravel 9 Vue Flash Message Example - geeksforgeeks.org</title>
        <link href="{{asset('css/app.css')}}" rel="stylesheet" type="text/css">
    </head>
    <body>
        <div id="app">
            <flash message=""></flash>
            <post-component></post-component>
        </div>
        <script src="{{asset('js/app.js')}}" ></script>
    </body>
</html>

Step 9: Run Development Server

Open terminal or cmd and execute the following command to start development server:

npm run dev

or 

npm run watch

Conclusion

In this example tutorial, we have learned how to show a flash message with Vue js in laravel apps.

Recommended Laravel Tutorials

RELATED ARTICLES

Most Popular

Recent Comments

ź°•ģ„œźµ¬ģ¶œģž„ė§ˆģ‚¬ģ§€ on How to store XML data into a MySQL database using Python?
źøˆģ²œźµ¬ģ¶œģž„ė§ˆģ‚¬ģ§€ on How to store XML data into a MySQL database using Python?
ź“‘ėŖ…ģ¶œģž„ģ•ˆė§ˆ on How to store XML data into a MySQL database using Python?
ź“‘ėŖ…ģ¶œģž„ģ•ˆė§ˆ on How to store XML data into a MySQL database using Python?
ė¶€ģ²œģ¶œģž„ģ•ˆė§ˆ on How to store XML data into a MySQL database using Python?
źµ¬ģ›”ė™ģ¶œģž„ģ•ˆė§ˆ on How to store XML data into a MySQL database using Python?
ź°•ģ„œźµ¬ģ¶œģž„ģ•ˆė§ˆ on How to store XML data into a MySQL database using Python?
ģ˜¤ģ‚°ģ¶œģž„ģ•ˆė§ˆ on How to store XML data into a MySQL database using Python?
ź“‘ėŖ…ģ¶œģž„ė§ˆģ‚¬ģ§€ on How to store XML data into a MySQL database using Python?
ģ•ˆģ–‘ģ¶œģž„ė§ˆģ‚¬ģ§€ on How to store XML data into a MySQL database using Python?
ė¶€ģ²œģ¶œģž„ģ•ˆė§ˆ on How to store XML data into a MySQL database using Python?
ė™ķƒ„ģ¶œģž„ģ•ˆė§ˆ on How to store XML data into a MySQL database using Python?
ģ„œģšøģ¶œģž„ģ•ˆė§ˆ on How to store XML data into a MySQL database using Python?
ė¶„ė‹¹ģ¶œģž„ģ•ˆė§ˆ on How to store XML data into a MySQL database using Python?
ė¶€ģ²œģ¶œģž„ģ•ˆė§ˆ on How to store XML data into a MySQL database using Python?
ķ™”ź³”ė™ģ¶œģž„ė§ˆģ‚¬ģ§€ on How to store XML data into a MySQL database using Python?
ź°•ģ„œźµ¬ģ¶œģž„ė§ˆģ‚¬ģ§€ on How to store XML data into a MySQL database using Python?
ź³ ģ–‘ģ¶œģž„ģ•ˆė§ˆ on How to store XML data into a MySQL database using Python?
ķ™”ģ„±ģ¶œģž„ė§ˆģ‚¬ģ§€ on How to store XML data into a MySQL database using Python?
ģ²œķ˜øė™ģ¶œģž„ė§ˆģ‚¬ģ§€ on How to store XML data into a MySQL database using Python?