Display a notification upon successfully submitting data in Laravel and Vue.js

Hello there; I am new to Laravel and Vue.js. I have encountered an issue when submitting a form with validation problems. The error message for a required input field, such as the "Brand Name" field, appears correctly, but after successfully submitting the form, only the first letter of the response message is displayed in uppercase, like "Y" instead of the full message "Your Data Added Successfully". Any idea how I can resolve this issue? Thank you. Here is my controller:

<?php

namespace App\Http\Controllers;

use App\PhoneBook;
use Illuminate\Http\Request;
use Validator;

class PhoneBookController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('phonebook');
    }
   }

    public function add(Request $request)
    {
        //prepare data for validation
        $validationarray=Validator::make($request->all(),
            [
                'name' => 'required',
                'phone' => 'required|min:2|required',
                'email' => 'required',
                ]
            ,[],[
                "name"=>"Brand Name",
                'phone' => 'phone',
                'email' => 'Email',
            ]);

        if($validationarray->fails())
        {
            foreach ($validationarray ->messages()->getMessages() as $field_name =>$message):
                $response['message']=$message;
            endforeach;
            $response['status']="failed";
            return response()->json($response);
        }

        $branddata=array(
            'name'          =>$request->name,
            'phone'     =>$request->phone,
            'email'     =>$request->email,
        );

        $add=PhoneBook::create($branddata)->id;
        if(false !=$add)
        {

            return response(['status'=>'success',"message"=>"Your Data Added Successfully"]);

        }else{
            return response(['status'=>'failed',"message"=>"Error Adding data please try again !!"]);


        }



    }

My route:

Route::post('phonebook/add',"PhoneBookController@add")->name("cart.deleteProductFromCart");

My view template code:

<template>
<div>
    <div class="modal fade" id="addData" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">New message</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <span v-if="list.status=='success'" >Record submitted successfully!</span>

                    <div   v-model="list.message" >{{list.message?list.message[0]:''}}</div>
                    <div class="form-group">

                        <label for="exampleInputEmail1">Brand Name</label>
                            <input type="text" name="name" v-model="list.name" class="form-control" id="exampleInputEmail1" placeholder="Example : Kia - Renault">
                            <p class="help-block">Example : Kia - Renault</p>

                    </div>
                        <div class="form-group">
                            <label  class="col-form-label">phone:</label>
                            <input type="text" name="phone" v-model="list.phone" class="form-control" id="reckipient-name">
                            <p class="help-block">Example : Kia - Renault</p>

                        </div>
                        <div class="form-group">
                            <label  class="col-form-label">email:</label>
                            <input type="text" class="form-control"  v-model="list.email" name="email" id="recikpient-name">
                            <p class="help-block">Example : Kia - Renault</p>

                        </div>

                </div>
                <div class="modal-footer">

                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" @click="save">Send message</button>
                </div>
            </div>
        </div>
    </div>
</div>
</template>


<script>
    export default {

        name: "addData",
        data: function () {
            return {
                list: {
                    name: '',
                    phone: '',
                    email: '',
                    message:'',

                },



            }
        },
        methods: {
            save: function () {
              axios.post('/phonebook/add',this.$data.list)
                    .then((response) => this.list.message=response.data.message)
                  .catch((error) => this.list.message=error.response.data.message)

            }
        }
    }

</script>
<style scoped>

</style>

[![enter image description here][1]][1]
[1]: https://i.sstatic.net/sZpDS.png

Answer №1

It's essential to return responses in JSON format for better data handling.

YourXYZController.php
....
$data = new stdClass;
$data->status = "success";
$data->message = "your message";

return response(json_encode($data));

When using Vuejs, make sure to handle async requests properly:

axios.post('YourXYZController URL', params)
        .then(response => {
          console.log(response)
        })
        .catch(error => {
          console.log(response)
        })
    })

Furthermore, always remember to inspect network requests and responses using the browser's network tab for troubleshooting purposes.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Customize data appearance in Django Admin interface

I am working with a model that has a json field. The data stored in this field may not always be pretty-printed, and I am okay with it as long as it is valid. However, when the data is displayed in Django admin, I would like it to be pretty printed for eas ...

Node.js method convention - invoking self-defined functions

Consider a scenario where a Node module contains two functions, func1() and func2(). It is necessary for func1 to make a call to func2 during its execution. In order to test func2 independently, I have included both func1 and func2 in the exports by setti ...

What is the best way to combine a string that is constructed across two separate callback functions using Mongoose in Node.js?

I am facing a situation where I have two interconnected models. When deleting a mongo document from the first model, I also need to delete its parent document. There is a possibility of an exception being thrown during the second deletion process. Regardl ...

Attempting to deploy my initial Google Cloud Function, encountering an error message indicating that Express is not detected

Currently in the process of deploying my first Google Cloud function, the code for which can be found here: https://github.com/rldaulton/GCF-Stripe/blob/master/Charge%20Customer/index.js The code starts with the following line: var app = require('e ...

Modifying the input placeholder color with ng-style

I am working on setting the color of my input placeholder using a dynamic color defined in a $scope variable in my controller for my HTML code. The $scope variable is structured as follows: $scope.primaryColor={"color":colorVar}; //colorVar represents th ...

Ways to dynamically implement a JSON configuration file in React JS during runtime

Looking to achieve text and image externalization in React? It's all about making changes in a JSON file that will reflect on your live Single Page Application (SPA). Here's an example of what the JSON file might look like: { "signup. ...

What is the best way to retrieve the total number of options within a dynamically generated <select> element using JavaScript in JSP?

To generate a page, I use the following code: <%List<String> someList = new ArrayList<String>(); someList = SQL();%> <select id=Select> <% for (int i =0; i < someList.size(); i++) { %> <option value=<%= someLis ...

Creating a Custom FlatList Content Container with React Native

Is it possible to customize FlatList items with a custom component? I want to create a setup where my FlatList items are encapsulated within a custom component similar to the following: <ScrollView pt={8} px={16} pb={128} > <Card e ...

Is an input field/text area necessary for the traditional copy to clipboard feature?

I needed to copy a section of text enclosed within an anchor tag to the clipboard. Following suggestions found online, I implemented the code below: HTML: <div class="organizer-link"> <i class="fa fa-link" id="copylink"></i> <a href ...

Tips for creating a hover effect on an icon within a CSS grid

I've just started learning to code and wanted to create a component for previewing/displaying a project I'm working on. I've been attempting to add a hover effect to my links such as the GitHubIcon and LaunchIcon, but so far, it's not w ...

Creating Apache Arrow vectors in TypeScript for writing data to a Table

Currently, I am in the process of creating a method that is designed to take a column of data, referred to as data: any[], and then pack it into an Arrow-typed Array Buffer for insertion into an Arrow table. To illustrate with an example, if we consider T ...

What could be the reason for a jQuery script failing to execute when included in a PHP include statement from a different PHP page?

I'm currently working with javascript and php to manage cookies across different pages. On one page, I have a script that sets a value in a cookie variable and I want to retrieve that value on another page. Let's say the first page is named page1 ...

Encountering a Runtime Exception During Composer Installation

I am in the process of setting up a new Laravel project. When I try to execute composer install, I encounter an error that is not very informative and I am unsure how to troubleshoot it. Here is the error message: $ composer install php artisan clear- ...

Error in Typescript: Attempting to access the property 'set' of an undefined value

Currently, I am in the process of setting up a basic example of push notifications on Android using Nativescript and Typescript. Although my code may seem a bit messy, I am struggling with properly rewriting "var Observable = require("data/observable");" a ...

Transferring information in React from a child component to its parent and then to another child

I'm currently developing my app using react.js and facing an issue with passing data between components. I have a Parent component (P) that needs to receive an array of objects from its child component (C1), then pass this data on to another child com ...

Tips for managing numerous Axios requests in JavaScript

I have a scenario where I need to send 3 axios calls simultaneously from the frontend to the backend using the axios.all function to modify a MONGO DB database. The challenge I am facing is ensuring that if one of the requests fails, none of the other requ ...

Having trouble with Angular + Rails combination: Angular can't seem to locate the controller

Issue: I am encountering an error in my Angular / Rails app. When trying to access a Rails controller function from the Angular controller, I receive the following error: Uncaught TypeError: tasks.moveOrder is not a function. Strangely, all other functions ...

Scrolling and adjusting window size while perfectly displaying images pixel by pixel using php and javascript

I'm currently working on a forum concept that will feature images. I'm looking to have the image displayed at default width and height, but also want users to be able to resize the window to view more of the image as needed. Additionally, I would ...

What steps should I take to create this animation?

So here's my concept: I envision a circle div positioned in the center with multiple small lines extending outwards, resembling rays of sunlight. How should I go about achieving this effect? Would implementing JavaScript or utilizing CSS3 animations b ...

How can I modify the date format using the Google Ajax Feed API?

Currently, I am utilizing Google's AJAX Feed API to pull data from an RSS feed. However, I am curious about how to modify the date format. The current format fed by "datePublished" appears as follows: Sun, 29 Jan 2012 23:37:38 -0800 Is there a way t ...