Search

CRUD's Tags

Angular 9 - CRUD Example with PHP and MySql
In this tutorial, you'll learn to engender an example REST API CRUD app with Angular 9/8, PHP and a MySQL database. Building a Backend with PHP and MySQL Database You will be engendering a simple REST API that fortifies GET, POST, PUT and EXPUNGE requests and sanction you to perform CRUD operations against a MySQL database to engender, read, update and efface records from a database. The Design of the MySQL Database For the application design, It's a simple interface for working with conveyance indemnification policies. For the sake of simplicity, you are only going to integrate the following attributes to the policies database table: number which stores to the indemnification policy number, amount which stores the indemnification quantity. This is of course far from being a consummate database design for a plenarily working indemnification system. Because at least you require to integrate other tables like employees, clients, coverage, conveyances and drivers etc. And additionally the relationships between all these entities. Building a Full-Stack PHP/Angular 9 App: Prerequisites In this tutorial we assume you have the following prerequisites: The MySQL database management system installed on your development machine, PHP installed on your system (both these first requirements are required by the back-end project), Node.js 8.9+ and NPM installed in your system. This is only required by your Angular 9 project. You also need to have a working experience with PHP and the different functions that will be used to create the SQL connection, getting the GET and POST data and returning JSON data in your code. You need to be familiar with TypeScript, a superset of JavaScript that's used with Angular 9. A basic knowledge of Angular 9 is preferable but not required since you'll go from the first step until your create a project that communicates with a PHP server. Creating the PHP Application Let's start by creating a simple PHP script that connects to a MySQL database and listens to API requests then responds accordingly by either fetching and returning data from the SQL table or insert, update and delete data from the database. Create a folder for your project: $ mkdir angular-9-php-app $ cd angular-9-php-app $ mkdir backend You create the angular-9-php-app that will contain the full front-end and back-end projects. Next, you navigate inside it and create the backend folder that will contain a simple PHP script that implements a simple CRUD REST API against a MySQL database. Next, navigate into your backend project and create an api folder. $ cd backend $ mkdir api Inside the api folder, create the following files: $ cd api $ touch database.php $ touch read.php $ touch create.php $ touch update.php $ touch delete.php Open the backend/api/database.php file and add the following PHP code step by step: <?php header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Methods: PUT, GET, POST, DELETE"); header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept"); These lines are used to add response headers such as CORS and the allowed methods (PUT, GET, DELETE and POST). Setting CORS to * will allow your PHP server to accept requests from another domain where the Angular 9 server is running from without getting blocked by the browser by reason of the Same Origin Policy. In development, you'll be running the PHP server from localhost:8080 port and Angular from localhost:4200 which are considered as two distinct domains. Next, add: define('DB_HOST', 'localhost'); define('DB_USER', 'root'); define('DB_PASS', 'YOUR_PASSWORD'); define('DB_NAME', 'mydb'); These variables hold the credentials that will be used to connect to the MySQL database and the name of the database. function connect() { $connect = mysqli_connect(DB_HOST ,DB_USER ,DB_PASS ,DB_NAME); if (mysqli_connect_errno($connect)) { die("Failed to connect:" . mysqli_connect_error()); } mysqli_set_charset($connect, "utf8"); return $connect; } $con = connect(); This will allow you to create a connection to the MySQL database using the mysqli extension. That's all for the database.php file Implementing the Read Operation Now, let's implement the read operation. Open the backend/api/read.php file and add the following code: This will fetch the list of policies from the database and return them as a JSON response. If there is an error it will return a 404 error. Implementing the Create Operation Let's now implement the create operation. Open the backend/api/create.php file and add the following code: <?php require 'database.php'; // Get the posted data. $postdata = file_get_contents("php://input"); if(isset($postdata) && !empty($postdata)) { // Extract the data. $request = json_decode($postdata); // Validate. if(trim($request->number) === '' || (float)$request->amount < 0) { return http_response_code(400); } // Sanitize. $number = mysqli_real_escape_string($con, trim($request->number)); $amount = mysqli_real_escape_string($con, (int)$request->amount); // Create. $sql = "INSERT INTO `policies`(`id`,`number`,`amount`) VALUES (null,'{$number}','{$amount}')"; if(mysqli_query($con,$sql)) { http_response_code(201); $policy = [ 'number' => $number, 'amount' => $amount, 'id' => mysqli_insert_id($con) ]; echo json_encode($policy); } else { http_response_code(422); } } Implementing the Update Operation Open the backend/api/update.php file and add the following code: <?php require 'database.php'; // Get the posted data. $postdata = file_get_contents("php://input"); if(isset($postdata) && !empty($postdata)) { // Extract the data. $request = json_decode($postdata); // Validate. if ((int)$request->id < 1 || trim($request->number) == '' || (float)$request->amount < 0) { return http_response_code(400); } // Sanitize. $id = mysqli_real_escape_string($con, (int)$request->id); $number = mysqli_real_escape_string($con, trim($request->number)); $amount = mysqli_real_escape_string($con, (float)$request->amount); // Update. $sql = "UPDATE `policies` SET `number`='$number',`amount`='$amount' WHERE `id` = '{$id}' LIMIT 1"; if(mysqli_query($con, $sql)) { http_response_code(204); } else { return http_response_code(422); } } Implementing the Delete Operation Open the backend/api/delete.php file and add the following code: <?php require 'database.php'; // Extract, validate and sanitize the id. $id = ($_GET['id'] !== null && (int)$_GET['id'] > 0)? mysqli_real_escape_string($con, (int)$_GET['id']) : false; if(!$id) { return http_response_code(400); } // Delete. $sql = "DELETE FROM `policies` WHERE `id` ='{$id}' LIMIT 1"; if(mysqli_query($con, $sql)) { http_response_code(204); } else { return http_response_code(422); } In all operations, we first require the database.php file for connecting to the MySQL database and then we implement the appropriate logic for the CRUD operation. Serving the PHP REST API Project You can next serve your PHP application using the built-in development server using the following command: $ php -S 127.0.0.1:8080 -t ./angular7-php-app/backend This will run a development server from the 127.0.0.1:8080 address. Creating the MySQL Database In your terminal, run the following command to start the mysql client: $ mysql -u root -p The client will prompt for the password that you configured when installing MySQL in your system. Next, run this SQL query to create a mydb database: mysql> create database mydb; Creating the policies SQL Table Next create the policies SQL table with two number and amount columns: mysql> create table policies( id int not null auto_increment, number varchar(20), amount float, primary key(id)); Now, you are ready to send GET, POST, PUT and DELETE requests to your PHP server running from the 127.0.0.1:8080 address. For sending test requests, you can use REST clients such as Postman or cURL before creating the Angular UI. Leave your server running and open a new terminal.
Django 3 CRUD Tutorial Example with MySQL and Bootstrap
Django 3 is released with full async support! In this tutorial, we'll see by example how to create a CRUD application from scratch and step by step. We'll see how to configure a MySQL database, enable the admin interface, and create the Django views. We'll be using Bootstrap 4 for styling. You'll learn how to: Implement CRUD operations, Configure and access a MySQL database, Create Django views, templates and urls, Style the UI with Bootstrap 4 Django 3 Features Django 3 comes with many new features such as: MariaDB support: Django now officially supports MariaDB 10.1+. You can use MariaDB via the MySQL backend, ASGI support for async programming, Django 3.0 provides support for running as an ASGI application, making Django fully async-capable Exclusion constraints on PostgreSQL: Django 3.0 adds a new ExclusionConstraint class which adds exclusion constraints on PostgreSQL, etc. Prerequisites Let's start with the prerequisites for this tutorial. In order to follow the tutorial step by step, you'll need a few requirements, such as: Basic knowledge of Python, Working knowledge of Django (django-admin.py and manage.py), A recent version of Python 3 installed on your system (the latest version is 3.7), MySQL database installed on your system. We will be using pip and venv which are bundled as modules in recent versions of Python so you don't actually need to install them unless you are working with old versions. If you are ready, lets go started! Step 1 - Creating a MySQL Database In this step, we'll create a mysql database for storing our application data. Open a new command-line interface and run the mysql client as follows: $ mysql -u root -p You'll be prompted for your MySQL password, enter it and press Enter. Next, create a database using the following SQL statement: mysql> create database mydb; We now have an empty mysql database! Step 2 - Initializing a New Virtual Environment In this step, we'll initialize a new virtual environment for installing our project packages in separation of the system-wide packages. Head back to your command-line interface and run the following command: $ python3 -m venv .env Next, activate your virtual environment using the following command: $ source .env/bin/activate At this point of our tutorial, we've a mysql database for persisting data and created a virtual environment for installing the project packages. Step 3 - Installing Django and MySQL Client In this step, we'll install django and mysql client from PyPI using pip in our activated virtual environment. Head back to your command-line interface and run the following command to install the django package: $ pip install django At the time of writing this tutorial, django-3.0.2 is installed. You will also need to install the mysql client for Python using pip: $ pip install mysqlclient Step 4 - Initializing a New Project In this step, we'll initialize a new django project using the django-admin. Head back to your command-line interface and run the following command: $ django-admin startproject djangoCrudExample Next, open the settings.py file and update the database settings to configure the mydb database: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mydb', 'USER': 'root', 'PASSWORD': '<YOUR_DB_PASSWORD>', 'HOST': 'localhost', 'PORT': '3306', } } Next, migrate the database using the following commands: $ cd djangoCrudExample $ python3 manage.py migrate You'll get a similar output: Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying sessions.0001_initial... OK This simply applies a set of builtin django migrations to create some necessary database tables or the working of django. Step 5 - Installing django-widget-tweaks In this step, we'll install django-widget-tweaks in our virtual environment. Head back to your command-line interface and run the following command: $ pip insll django-widget-tweaks Next, open the settings.py file and add the application to the installed apps: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'widget_tweaks' ] Step 6 - Creating an Admin User In this step, we'll create an admin user that will allow us to access the admin interface of our app using the following command: $ python manage.py createsuperuser Provide the desired username, email and password when prompted: Username (leave blank to use 'ahmed'): Email address: ahmed@gmail.com Password: Password (again): Superuser created successfully. Step 7 - Creating a Django Application In this step, we'll create a django application. Head back to your command-line interface, and run the following command: $ python manage.py startapp crudapp Next, you need to add it in the settings.py file as follows: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'widget_tweaks', 'crudapp' ] Step 8 - Creating the Model(s) In this step. we'll create the database model for storing contacts. Open the crudapp/models.py file and add the following code: from django.db import models class Contact(models.Model): firstName = models.CharField("First name", max_length=255, blank = True, null = True) lastName = models.CharField("Last name", max_length=255, blank = True, null = True) email = models.EmailField() phone = models.CharField(max_length=20, blank = True, null = True) address = models.TextField(blank=True, null=True) description = models.TextField(blank=True, null=True) createdAt = models.DateTimeField("Created At", auto_now_add=True) def __str__(self): return self.firstName After creating these model, you need to create migrations using the following command: $ python manage.py makemigrations You should get a similar output: crudapp/migrations/0001_initial.py - Create model Contact Next, you need to migrate your database using the following command: $ python manage.py migrate You should get a similar output: Applying crudapp.0001_initial... OK Step 9 - Creating a Form In this step, we'll create a form for creating a contact. In the crudapp folder, create a forms.py file and add the following code: from django import forms from .models import Contact class ContactForm(forms.ModelForm): class Meta: model = Contact fields = "__all__" We import the Contact model from the models.py file. We created a class called ContactForm, subclassing Django’s ModelForms from the django.forms package and specifying the model we want to use. We also specified that we will be using all fields in the Contact model. This will make it possible for us to display those fields in our templates. Step 10 - Creating the Views In this step, we'll create the views for performing the CRUD operations. Open the crudapp/views.py file and add: from django.shortcuts import render, redirect, get_object_or_404 from .models import Contact from .forms import ContactForm from django.views.generic import ListView, DetailView Next, add: class IndexView(ListView): template_name = 'crudapp/index.html' context_object_name = 'contact_list' def get_queryset(self): return Contact.objects.all() class ContactDetailView(DetailView): model = Contact template_name = 'crudapp/contact-detail.html' Next, add: def create(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): form.save() return redirect('index') form = ContactForm() return render(request,'crudapp/create.html',{'form': form}) def edit(request, pk, template_name='crudapp/edit.html'): contact = get_object_or_404(Contact, pk=pk) form = ContactForm(request.POST or None, instance=post) if form.is_valid(): form.save() return redirect('index') return render(request, template_name, {'form':form}) def delete(request, pk, template_name='crudapp/confirm_delete.html'): contact = get_object_or_404(Contact, pk=pk) if request.method=='POST': contact.delete() return redirect('index') return render(request, template_name, {'object':contact}) Step 11 - Creating Templates Open the settings.py file and add os.path.join(BASE_DIR, 'templates') to the TEMPLATES array: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] This will tell django to look for the templates in the templates folder. Next, inside the crudapp folder create a templates folder: $ mkdir templates Next, inside the templates folder, create the following files: base.html confirm_delete.html edit.html index.html create.html contact-detail.html By running the following commands from the root of your project: $ mkdir templates $ cd templates $ mkdir crudapp $ touch crudapp/base.html $ touch crudapp/confirm_delete.html $ touch crudapp/edit.html $ touch crudapp/index.html $ touch crudapp/create.html $ touch crudapp/contact-detail.html Open the crudapp/templates/base.html file and the add: <!DOCTYPE html> <html> <head> <title>Django 3 CRUD Example - LaravelCode</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> </head> <body> {% block content %} {% endblock %} <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script> </body> </html> Next, open the crudapp/templates/index.html file and the add: {% extends 'crudapp/base.html' %} {% block content %} <div class="container-fluid"> <div class="row"> <div class="col-md-1 col-xs-1 col-sm-1"></div> <div class="col-md-10 col-xs-10 col-sm-10"> <h3 class="round3" style="text-align:center;">Contacts</h3> </div> <div class="col-md-1 col-xs-1 col-sm-1"></div> </div> <div class="row"> <div class="col-md-10 col-xs-10 col-sm-10"></div> <div class="col-md-2 col-xs-1 col-sm-1"> <br /> <a href="{% url 'create' %}"> <button type="button" class="btn btn-success"> <span class="glyphicon glyphicon-plus"></span> </button> </a> </div> </div> <br /> {% for contact in contact_list %} <div class="row"> <div class="col-md-1 col-xs-1 col-sm-1"></div> <div class="col-md-7 col-xs-7 col-sm-7"> <ul class="list-group"> <li class="list-group-item "> <a href="{% url 'detail' contact.pk %}"> {{ contact.firstName }} {{contact.lastName}} </a> <span class="badge"></span> </li> </ul> <br> </div> <div class="col-md-1 col-xs-1 col-sm-1"> <a href="{% url 'detail' contact.pk %}"> <button type="button" class="btn btn-info"> <span class="glyphicon glyphicon-open"></span> </button> </a> </div> <div class="col-md-1"> <a href="{% url 'edit' contact.pk %}"> <button type="button" class="btn btn-info"> <span class="glyphicon glyphicon-pencil"></span> </button> </a> </div> <div class="col-md-1"> <a href="{% url 'delete' contact.pk %}"> <button type="button" class="btn btn-danger"> <span class="glyphicon glyphicon-trash"></span> </button> </a> </div> <div class="col-md-1 col-xs-1 col-sm-1"></div> </div> {% endfor %} </div> {% endblock %} Next, open the crudapp/templates/create.html file and the add: {% load widget_tweaks %} <!DOCTYPE html> <html> <head> <title>Posts</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <style type="text/css"> <style> </style> </style> </head> <body> <div class="container-fluid"> <div class="row"> <div class="col-md-1 col-xs-1 col-sm-1"></div> <div class="col-md-10 col-xs-10 col-sm-10 "> <br /> <h6 style="text-align:center;"> <font color="red"> All fields are required</font> </h6> </div> <div class="col-md-1 col-xs-1 col-sm-1"> </div> </div> <div class="row"> <div class="col-md-1 col-xs-1 col-sm-1"></div> <div class="col-md-10 col-xs-10 col-sm-10"> <form method="post" novalidate> {% csrf_token %} {% for hidden_field in form.hidden_fields %} {{ hidden_field }} {% endfor %} {% for field in form.visible_fields %} <div class="form-group"> {{ field.label_tag }} {% render_field field class="form-control" %} {% if field.help_text %} <small class="form-text text-muted">{{ field.help_text }}</small> {% endif %} </div> {% endfor %} <button type="submit" class="btn btn-primary">post</button> </form> <br> </div> <div class="col-md-1 col-xs-1 col-sm-1"></div> </div> </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script> </body> </html> Next, open the crudapp/templates/edit.html file and the add: {% load widget_tweaks %} <!DOCTYPE html> <html> <head> <title>Edit Contact</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <style type="text/css"> <style> </style> </style> </head> <body> <div class="container-fluid"> <div class="row"> <div class="col-md-1 col-xs-1 col-sm-1"></div> <div class="col-md-10 col-xs-10 col-sm-10 "> <br /> <h6 style="text-align:center;"> <font color="red"> All fields are required</font> </h6> </div> <div class="col-md-1 col-xs-1 col-sm-1"> </div> </div> <div class="row"> <div class="col-md-1 col-xs-1 col-sm-1"></div> <div class="col-md-10 col-xs-10 col-sm-10"> <form method="post" novalidate> {% csrf_token %} {% for hidden_field in form.hidden_fields %} {{ hidden_field }} {% endfor %} {% for field in form.visible_fields %} <div class="form-group"> {{ field.label_tag }} {% render_field field class="form-control" %} {% if field.help_text %} <small class="form-text text-muted">{{ field.help_text }}</small> {% endif %} </div> {% endfor %} <button type="submit" class="btn btn-primary">submit</button> </form> <br> </div> <div class="col-md-1 col-xs-1 col-sm-1"></div> </div> </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script> </body> </html> Next, open the crudapp/templates/confirm_delete.html file and the add: {% extends 'crudapp/base.html' %} {% block content %} <div class="container"> <div class="row"></div> <br /> <div class="row"> <div class="col-md-2 col-xs-2 col-sm-2"></div> <div class="col-md-10 col-xs-10 col-sm-10"> <form method="post"> {% csrf_token %} <div class="form-row"> <div class="alert alert-warning"> Are you sure you want to delete {{ object }}? </div> </div> <button type="submit" class="btn btn-danger"> <span class="glyphicon glyphicon-trash"></span> </button> </form> </div> </div> </div> {% endblock %} Step 12 - Creating URLs In this step, we'll create the urls to access our CRUD views. Go to the urls.py file and update it as follows: from django.contrib import admin from django.urls import path from crudapp import views urlpatterns = [ path('admin/', admin.site.urls), path('contacts/', views.IndexView.as_view(), name='index'), path('contacts/<int:pk>/', views.ContactDetailView.as_view(), name='detail'), path('contacts/edit/<int:pk>/', views.edit, name='edit'), path('contacts/create/', views.create, name='create'), path('contacts/delete/<int:pk>/', views.delete, name='delete'), ] Step 11 - Running the Local Development Server In this step, we'll run the local development server for playing with our app without deploying it to the web. Head back to your command-line interface and run the following command: $ python manage.py runserver Next, go to the http://localhost:8000/ address with a web browser. Conclusion In this Django 3 tutorial, we have initialized a new Django project, created and migrated a MySQL database, and built a simple CRUD interface.
VueJs CRUD Example using MongoDB | Express.js | Vue.js | Node.js
This is a step by step MEVN stack tutorial, in this tutorial, we are going to learn how to engender MEVN stack app. (MongoDB, Express.js, Vue.js, Node.js). I will show you how to engender a Full-stack single page application with Vue from scratch. We will engender a simple yet best Student Record Management system. This system efficiently sanctions users to perform CRUD (ENGENDER, READ, UPDATE & EFFACE) operations. We will create our server using Node and Express.js and store student records. We will use MongoDB. We will manage the front-end of the application with Vue.js. So, let us start coding the MEVN Stack app with a practical example. Create a New Vue Project To install Vue project, we must have Vue CLI installed on our development system. Run the following command to install Vue CLI: # npm npm install -g @vue/cli # yarn yarn global add @vue/cli Use the following command to install the vue project. vue create vue-mevn-stack-app Head over to vue project: cd vue-mevn-stack-app Run command to start the app on the browser: npm run serve Adding Bootstrap in Vue 2 Let us run the below command to install the Bootstrap 4 UI Framework. npm install bootstrap # or yarn add bootstrap Import the Bootstrap framework path inside the main.js file. Now, you can use Bootstrap UI components in your vue app. import Vue from 'vue' import App from './App.vue' import router from './router' import 'bootstrap/dist/css/bootstrap.min.css' Vue.config.productionTip = false new Vue({ router, render: h => h(App) }).$mount('#app') Build Vue Components Head over to src/components directory, here we have to create the following components. These components will handle the data in our full-stack Vue.Js application. CreateComponent.vue EditComponent.vue ListComponent.vue Open src/CreateComponent.vue file and add the following code inside of it. <template> <div class="row justify-content-center"> <div class="col-md-6"> <!-- Content goes here --> </div> </div> </template> <script> export default { data() { return { } } } </script> </div> Open src/EditComponent.vue file and place code inside of it. <template> <div class="row justify-content-center"> <div class="col-md-6"> <!-- Update Student content --> </div> </div> </template> <script> export default { data() { return { } } } </script> Open src/ListComponent.vue file and add the below code in it. <template> <div class="row justify-content-center"> <div class="col-md-6"> <!-- Display Student List --> </div> </div> </template> <script> export default { data() { return { } } } </script> Enable Vue Router Open src/router/index.js and replace the existing code with the following code. import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter) const routes = [ { path: '/', name: 'home', component: () => import('../components/CreateComponent') }, { path: '/view', name: 'view', component: () => import('../components/ListComponent') }, { path: '/edit/:id', name: 'edit', component: () => import('../components/EditComponent') } ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router Setting Up Navigation with Bootstrap and Router View in Vue Go to src/App.vue file, here we define the Bootstrap Navigation component, router-view directive and the router-link directive. The <router-link> is the component for facilitating user navigation in a router-enabled vue app. The <router-view> component is the main component that is responsible for rendering the matched component for the provided path. <template> <div> <!-- Nav bar --> <nav class="navbar navbar-dark bg-primary justify-content-between flex-nowrap flex-row"> <div class="container"> <a class="navbar-brand float-left">MEVN Stack Example | LaravelCode</a> <ul class="nav navbar-nav flex-row float-right"> <li class="nav-item"> <router-link class="nav-link pr-3" to="/">Create Student</router-link> </li> <li class="nav-item"> <router-link class="nav-link" to="/view">View Students</router-link> </li> </ul> </div> </nav> <!-- Router view --> <div class="container mt-5"> <router-view></router-view> </div> </div> </template> Add Axios in Vue.js 2 to Handle HTTP Requests Run command to install Axios: npm install axios # or yarn add axios Axios is a promise based HTTP client for the browser and node.js,  Build Form in Vue with Bootstrap 4 We require to store the data in the MEVN stack app, so we need to build a vue form using Bootstrap Form component. Check out our previous tutorial detailed tutorial on – Form Validation in Vue with Vuelidate. Open components/CreateComponent.vue file, then place the following code in it. <template> <div class="row justify-content-center"> <div class="col-md-6"> <h3 class="text-center">Create Student</h3> <form @submit.prevent="handleSubmitForm"> <div class="form-group"> <label>Name</label> <input type="text" class="form-control" v-model="student.name" required> </div> <div class="form-group"> <label>Email</label> <input type="email" class="form-control" v-model="student.email" required> </div> <div class="form-group"> <label>Phone</label> <input type="text" class="form-control" v-model="student.phone" required> </div> <div class="form-group"> <button class="btn btn-danger btn-block">Create</button> </div> </form> </div> </div> </template> <script> export default { data() { return { student: { name: '', email: '', phone: '' } } }, methods: { handleSubmitForm() { } } } </script> We created a basic form with name, email and phone number field. We created a beautiful form using Bootstrap form component. The student object works with two-way data binding approach; it merely means that any data-related changes affecting the model are immediately propagated to the matching view. Here is the form which you can check in the browser. Setting up Node Server Environment Now, we need to create REST APIs using Node + Express & MongoDB in Vue application. Create backend folder at the root of Vue project. mkdir backend && cd backend Generate separate package.json for node server. npm init Run command to install the following dependencies for Node/Express js. npm i body-parser cors express mongoose Also, install a nodemon server as a development dependency. So that we do not need to restart every time, we change our server code. Install nodemon as a development dependency, It automates the server starting process. npm install nodemon # or yarn add nodemon Configure & Start MongoDB Database Create backend/database.js file at the root of your node application. Next, add the given code in it. module.exports = { db: 'mongodb://localhost:27017/vuecrudmevn' } In this tutorial, we are working with MongoDB to store students data, so you must set up MongoDB on your development system. You can follow this tutorial for the installation guidance at Install MongoDB on macOS, Linux and Windows. Open the terminal window and run the following command to start the MongoDB on your local machine. mongod --config /usr/local/etc/mongod.conf brew services start mongodb-community@4.2 mongo Create Mongoose Model Create models/Student.js and paste the below code inside the file. We will define name, email and phone values inside the Student model. const mongoose = require('mongoose'); const Schema = mongoose.Schema; let studentSchema = new Schema({ name: { type: String }, email: { type: String }, phone: { type: Number }, }, { collection: 'students' }) module.exports = mongoose.model('Student', studentSchema) Create Route in Node/Express App Create a backend/routes directory; here, we have to create student.route.js file and place all the given below code inside of it. const express = require('express'); const studentRoute = express.Router(); // Student model let StudentModel = require('../models/Student'); studentRoute.route('/').get((req, res) => { StudentModel.find((error, data) => { if (error) { return next(error) } else { res.json(data) } }) }) studentRoute.route('/create-student').post((req, res, next) => { StudentModel.create(req.body, (error, data) => { if (error) { return next(error) } else { res.json(data) } }) }); studentRoute.route('/edit-student/:id').get((req, res) => { StudentModel.findById(req.params.id, (error, data) => { if (error) { return next(error) } else { res.json(data) } }) }) // Update student studentRoute.route('/update-student/:id').post((req, res, next) => { StudentModel.findByIdAndUpdate(req.params.id, { $set: req.body }, (error, data) => { if (error) { return next(error); } else { res.json(data) console.log('Student successfully updated!') } }) }) // Delete student studentRoute.route('/delete-student/:id').delete((req, res, next) => { StudentModel.findByIdAndRemove(req.params.id, (error, data) => { if (error) { return next(error); } else { res.status(200).json({ msg: data }) } }) }) module.exports = studentRoute; We defined the routes these routes will communicate with the server using the Axios library. We can perform CRUD operation using the GET, POST, UPDATE & DELETE methods. Create the backend/app.js file and place the following code that contains the Node server settings. let express = require('express'), cors = require('cors'), mongoose = require('mongoose'), database = require('./database'), bodyParser = require('body-parser'); // Connect mongoDB mongoose.Promise = global.Promise; mongoose.connect(database.db, { useNewUrlParser: true, useUnifiedTopology: true }).then(() => { console.log("Database connected") }, error => { console.log("Database could't be connected to: " + error) } ) const studentAPI = require('../backend/routes/student.route') const app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cors()); // API app.use('/api', studentAPI) // Create port const port = process.env.PORT || 4000; const server = app.listen(port, () => { console.log('Connected to port ' + port) }) // Find 404 app.use((req, res, next) => { next(createError(404)); }); // error handler app.use(function (err, req, res, next) { console.error(err.message); if (!err.statusCode) err.statusCode = 500; res.status(err.statusCode).send(err.message); }); Also, don’t forget to register the app.js value inside the “main” property in package.json file. { "name": "vue-mevn-stack", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "dependencies": { "body-parser": "^1.19.0", "cors": "^2.8.5", "express": "^4.17.1", "mongoose": "^5.9.10" }, "devDependencies": { "nodemon": "^2.0.3" } } Start Node/Express App We have built following API using Node and Express in Vue.js. Method API GET http://localhost:4000/api POST /api/create-student GET /api/edit-student/:id POST /api/update-student/:id DELETE /api/delete-student/:id Open a new terminal window and start the MongoDB: mongo Open a new terminal window and start the nodemon server: nodemon You can view server running on http://localhost:4000/api Open another terminal window and start the vue app: npm run serve You can view vue app running on http://localhost:8080 Create Student Data with Axios POST The Axios post method takes the REST API and makes the POST request to the server. It creates the student data that we are adding in the mongoDB database. Once the data is sent to the server, you can then check the stored data on http://localhost:4000/api Add the given below code inside the components/CreateComponent.vue file. <template> <div class="row justify-content-center"> <div class="col-md-6"> <h3 class="text-center">Create Student</h3> <form @submit.prevent="handleSubmitForm"> <div class="form-group"> <label>Name</label> <input type="text" class="form-control" v-model="student.name" required> </div> <div class="form-group"> <label>Email</label> <input type="email" class="form-control" v-model="student.email" required> </div> <div class="form-group"> <label>Phone</label> <input type="text" class="form-control" v-model="student.phone" required> </div> <div class="form-group"> <button class="btn btn-danger btn-block">Create</button> </div> </form> </div> </div> </template> <script> import axios from "axios"; export default { data() { return { student: { name: '', email: '', phone: '' } } }, methods: { handleSubmitForm() { let apiURL = 'http://localhost:4000/api/create-student'; axios.post(apiURL, this.student).then(() => { this.$router.push('/view') this.student = { name: '', email: '', phone: '' } }).catch(error => { console.log(error) }); } } } </script> Show Data List & Delete Data in Vue Now, we will show the data in the tabular form using Bootstrap Table components, and we will make the axios.get() request to render the data from the server. Add the given below code inside the components/ListComponent.vue file. <template> <div class="row"> <div class="col-md-12"> <table class="table table-striped"> <thead class="thead-dark"> <tr> <th>Name</th> <th>Email</th> <th>Phone</th> <th>Actions</th> </tr> </thead> <tbody> <tr v-for="student in Students" :key="student._id"> <td>{{ student.name }}</td> <td>{{ student.email }}</td> <td>{{ student.phone }}</td> <td> <router-link :to="{name: 'edit', params: { id: student._id }}" class="btn btn-success">Edit </router-link> <button @click.prevent="deleteStudent(student._id)" class="btn btn-danger">Delete</button> </td> </tr> </tbody> </table> </div> </div> </template> <script> import axios from "axios"; export default { data() { return { Students: [] } }, created() { let apiURL = 'http://localhost:4000/api'; axios.get(apiURL).then(res => { this.Students = res.data; }).catch(error => { console.log(error) }); }, methods: { deleteStudent(id){ let apiURL = `http://localhost:4000/api/delete-student/${id}`; let indexOfArrayItem = this.Students.findIndex(i => i._id === id); if (window.confirm("Do you really want to delete?")) { axios.delete(apiURL).then(() => { this.Students.splice(indexOfArrayItem, 1); }).catch(error => { console.log(error) }); } } } } </script> <style> .btn-success { margin-right: 10px; } </style> To delete the student object from the database, we defined the deleteStudent() function and bound it to click event with an id parameter. The apiURL contains the api/delete-student/:id API, to find out the index of the clicked student data index from the Students array, we took the help of findIndex() method. Update Data with POST Request Add the following code inside the components/EditComponent.vue file. <template> <div class="row justify-content-center"> <div class="col-md-6"> <h3 class="text-center">Update Student</h3> <form @submit.prevent="handleUpdateForm"> <div class="form-group"> <label>Name</label> <input type="text" class="form-control" v-model="student.name" required> </div> <div class="form-group"> <label>Email</label> <input type="email" class="form-control" v-model="student.email" required> </div> <div class="form-group"> <label>Phone</label> <input type="text" class="form-control" v-model="student.phone" required> </div> <div class="form-group"> <button class="btn btn-danger btn-block">Update</button> </div> </form> </div> </div> </template> <script> import axios from "axios"; export default { data() { return { student: { } } }, created() { let apiURL = `http://localhost:4000/api/edit-student/${this.$route.params.id}`; axios.get(apiURL).then((res) => { this.student = res.data; }) }, methods: { handleUpdateForm() { let apiURL = `http://localhost:4000/api/update-student/${this.$route.params.id}`; axios.post(apiURL, this.student).then((res) => { console.log(res) this.$router.push('/view') }).catch(error => { console.log(error) }); } } } </script> i hope you like this article.
VueJs CRUD using Google Firebase
This is a step by step tutorial that explicates how to build a Vue.js 2+ CRUD web application utilizing Firebase database. We are going to engender a rudimental customer records management system, in which a utilizer can perform CRUD operations and store the data into the Cloud Firestore. Firebase abbreviates the pain of maintaining the backend server because Firebase is Backend-as-a-accommodation. It gives liberation to developers to fixate on enhancing the utilizer experiences rather than maintaining the backend or server. It updates the data in authentic-time even it updates the data on all the connected contrivances as anon as the information updates on the cloud Firestore, and the resplendent thing is you don’t have to indite the APIs. Here are some of the Firebase Features: Push notifications Ready-made API Realtime data update Enhanced security Cloud storage Easy A/B testing Analytics monitoring Easy server management Offline access to WEB SDK Hosting and cloud storage Authentication with Email & password, Google, Facebook, & Github Vue.js Firebase CRUD Web App Example We require following tools and frameworks: Vue CLI v4.3.1 Vue 2.6.11 Firebase Bootstrap 4 IDE or Code Editor Setting up Firebase Project We need firebase configuration details to connect Firebase with the Vue.js app. So, in this step, we will create a Firebase project inside the Firebase dashboard. Click “Create a project”. Click on “Add project”, we don’t need to enable analytics for this demo. Click on “Continue” to generate the project. Click on the web icon. Provide the app nickname and click on “Next”. Copy Firebase configuration details, It connects Vue with Firebase. Click on “Database” => “Cloud Firestore” and click on the “Create Database”. Configure the security rules in test mode. Next, create a “users” collection. You can make as many collection as you want. The collection is a set of document that contains specific information or data. Create Vue App with Vue CLI The Vue CLI offers the conventional tooling for rapid Vue.js development. Run the command in the terminal to install Vue CLI. npm install -g @vue/cli # or yarn global add @vue/cli Verify the vue-cli installed version: vue --version Create a brand new Vue.js project from scratch using the below command. vue create vue-firebase-crud-app Answer the following question asked by Vue CLI: # ? Please pick a preset: Manually select features # ? Check the features needed for your project: Babel, Router, CSS Pre-processors, Linter # ? Use history mode for router? (Requires proper server setup for index fallback in production) Yes # ? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Sass/SCSS (with dart-sass) # ? Pick a linter / formatter config: Basic # ? Pick additional lint features: Lint on save # ? Where do you prefer placing config for Babel, ESLint, etc.? In package.json # ? Save this as a preset for future projects? (y/N) No Head over to the newly installed project folder. cd vue-firebase-crud-app Run the command to see the vue app on the browser. npm run serve App can be seen at: Local: http://localhost:8080/ Network: http://192.168.0.103:8080/ Add Bootstrap 4 in Vue Open the terminal and run the command to install Bootstrap in Vue. npm install bootstrap # or yarn add bootstrap Add the Import path in the main.js file. It will let us use the Bootstrap components throughout the vue application. import Vue from 'vue' import App from './App.vue' import router from './router' import 'bootstrap/dist/css/bootstrap.min.css' Vue.config.productionTip = false new Vue({ router, render: h => h(App) }).$mount('#app') Creating Vue Components To manage the data or our CRUD application, we need to create the following files inside the “components” folder. UserCreate.vue UserEdit.vue UserList.vue A regular vue component seems like this: <template> <div class="row justify-content-center"> <div class="col-md-6"> <!-- Content goes here --> </div> </div> </template> <script> export default { data() { return { } } } </script> </div> Create Vue Router for Firebase CRUD Demo App Go to router/index.js file and replace with the given code. We are adding the particular url path with its associated component. import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter) const routes = [ { path: '/', name: 'add', component: () => import('../components/UserCreate') }, { path: '/list', name: 'list', component: () => import('../components/UserList') }, { path: '/edit/:id', name: 'edit', component: () => import('../components/UserEdit') } ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router Add Navigation with Router View The Bootstrap navigation component creates the beautiful header with nav items. The router-link directive navigates to the specific page, and the router-view directive displays the associated component with its router. Open src/App.vue file, add the following code in it. <template> <div> <nav class="navbar navbar-dark bg-dark justify-content-between flex-nowrap flex-row"> <div class="container"> <a class="navbar-brand float-left">Firebase Vue CRUD Example</a> <ul class="nav navbar-nav flex-row float-right"> <li class="nav-item"> <router-link class="nav-link pr-3" to="/">Add User</router-link> </li> <li class="nav-item"> <router-link class="nav-link" to="/list">View Users</router-link> </li> </ul> </div> </nav> <div class="container mt-5"> <router-view></router-view> </div> </div> </template> Create Interactive Vue Form with Bootstrap Add the following code inside components/UserCreate.vue file. <template> <div class="row justify-content-center"> <div class="col-md-5"> <h3 class="text-center">Add User</h3> <form @submit.prevent="onFormSubmit"> <div class="form-group"> <label>Name</label> <input type="text" class="form-control" v-model="user.name" required> </div> <div class="form-group"> <label>Email</label> <input type="email" class="form-control" v-model="user.email" required> </div> <div class="form-group"> <label>Phone</label> <input type="text" class="form-control" v-model="user.phone" required> </div> <div class="form-group"> <button class="btn btn-primary btn-block">Add User</button> </div> </form> </div> </div> </template> <script> export default { data() { return { user: { name: '', email: '', phone: '' } } }, methods: { onFormSubmit() { alert(JSON.stringify(this.user)) } } } </script> Install and Set up Firebase in Vue Install Firebase plugin in vue.js, it makes the communication between Vue and Cloud Firestore. npm install firebase Create a src/firebaseDb.js file then add the following code to establish the real-time database connection in vue with your Firebase configurations details. import * as firebase from 'firebase'; const firebaseConfig = { apiKey: "api-key", authDomain: "project-id.firebaseapp.com", databaseURL: "https://project-id.firebaseio.com", projectId: "project-id", storageBucket: "project-id.appspot.com", messagingSenderId: "sender-id", appId: "app-id", measurementId: "G-measurement-id" } const firebaseApp = firebase.initializeApp(firebaseConfig); export const db = firebaseApp.firestore(); Add Data in Cloud Firestore We will use the firestore collection() method to add the Data in the Cloud Firestore Database. Add the following code inside the UserCreate.vue file. <template> <div class="row justify-content-center"> <div class="col-md-5"> <h3 class="text-center">Add User</h3> <form @submit.prevent="onFormSubmit"> <div class="form-group"> <label>Name</label> <input type="text" class="form-control" v-model="user.name" required> </div> <div class="form-group"> <label>Email</label> <input type="email" class="form-control" v-model="user.email" required> </div> <div class="form-group"> <label>Phone</label> <input type="text" class="form-control" v-model="user.phone" required> </div> <div class="form-group"> <button class="btn btn-primary btn-block">Add User</button> </div> </form> </div> </div> </template> <script> import { db } from '../firebaseDb'; export default { data() { return { user: { } } }, methods: { onFormSubmit(event) { event.preventDefault() db.collection('users').add(this.user).then(() => { alert("User successfully created!"); this.user.name = '' this.user.email = '' this.user.phone = '' }).catch((error) => { console.log(error); }); } } } </script> Display Data & Delete Data Object from Firestore The Bootstrap Table components is famously employed for representing the user data that we fetched from the Cloud Firestore using the collection(‘users’).get() method. The router-link directive is taking us to the user details page, and we passed the user key/id in the router link. To delete the user data object from Firestore, we passed the data key to the deleteUser(key) method. The data object can be removed using the delete() method. Add the following code inside the UserList.vue file. <template> <div class="row"> <div class="col-md-12"> <table class="table table-striped"> <thead> <tr> <th>Name</th> <th>Email</th> <th>Phone</th> <th>Actions</th> </tr> </thead> <tbody> <tr v-for="user in Users" :key="user.key"> <td>{{ user.name }}</td> <td>{{ user.email }}</td> <td>{{ user.phone }}</td> <td> <router-link :to="{name: 'edit', params: { id: user.key }}" class="btn btn-primary">Edit </router-link> <button @click.prevent="deleteUser(user.key)" class="btn btn-danger">Delete</button> </td> </tr> </tbody> </table> </div> </div> </template> <script> import { db } from '../firebaseDb'; export default { data() { return { Users: [] } }, created() { db.collection('users').onSnapshot((snapshotChange) => { this.Users = []; snapshotChange.forEach((doc) => { this.Users.push({ key: doc.id, name: doc.data().name, email: doc.data().email, phone: doc.data().phone }) }); }) }, methods: { deleteUser(id){ if (window.confirm("Do you really want to delete?")) { db.collection("users").doc(id).delete().then(() => { console.log("Document deleted!"); }) .catch((error) => { console.error(error); }) } } } } </script> <style> .btn-primary { margin-right: 12px; } </style> Update Data in Cloud Firestore The $route.params.id gets the current user’s object id from the URL. Pass it inside the doc() method and access the get() function to render the single document from the Firestore database. The onUpdateForm() function updates the Firestore data object in the data collection. The user redirects to the user’s list view page once successfully updated. Add the following code inside the UserEdit.vue file. <template> <div class="row justify-content-center"> <div class="col-md-5"> <h3 class="text-center">Update User</h3> <form @submit.prevent="onUpdateForm"> <div class="form-group"> <label>Name</label> <input type="text" class="form-control" v-model="user.name" required> </div> <div class="form-group"> <label>Email</label> <input type="email" class="form-control" v-model="user.email" required> </div> <div class="form-group"> <label>Phone</label> <input type="text" class="form-control" v-model="user.phone" required> </div> <div class="form-group"> <button class="btn btn-primary btn-block">Add User</button> </div> </form> </div> </div> </template> <script> import { db } from '../firebaseDb'; export default { data() { return { user: { } } }, created() { let dbRef = db.collection('users').doc(this.$route.params.id); dbRef.get().then((doc) => { this.user = doc.data(); }).catch((error) => { console.log(error) }) }, methods: { onUpdateForm(event) { event.preventDefault() db.collection('users').doc(this.$route.params.id) .update(this.user).then(() => { console.log("User successfully updated!"); this.$router.push('/list') }).catch((error) => { console.log(error); }); } } } </script> i hope you like this article.
React CRUD Example using MongoDB | Express | React | NodeJs
Today, I am going to teach you how to build React CRUD web application from scratch. Along with that, we will learn how to set up a Node server and create REST APIs using Node and Express.js. React MERN Stack Example In this MERN stack tutorial, we will create a basic Student app from starting to finish. This app will allow us to create student, show students list, update student, and delete a student from the MongoDB database. Before we move further let’s understand What is MERN stack? MERN Stack stands for MongoDB, Express, React, Node.js and this combined stack is known as MERN stack. Stack Detail MongoDB A document-oriented database programme based on NoSQL. Express It’s a robust Node.js web application framework that helps in creating powerful REST APIs. React A JavaScript library used to create beautiful and interactive user interfaces developed by Facebook and the community of individual developers. Node It’s a JavaScript runtime environment built on Google Chrome’s V8 engine, and it compiles js at the runtime. Tutorial Objective Setting up React project Creating components in React Building and working with React routers Working with React-Bootstrap Getting started with React forms Consuming REST APIs in React app Getting started with Create, Read, Update and Delete in React Setting up a Node and Express server MongoDB set up in MERN stack project Creating REST APIs using Express.js Making HTTP requests with React Axios library Prerequisites Before getting started with this tutorial, you must be aware of the fundamentals of React.js and HTML, CSS, JavaScript, TypeScript, or ES6. Check out React’s official website to know more about its features, central concepts, and API reference here. In order to build MERN Stack web application, you must have Node.js installed on your system. Ignore this step if Node is already installed otherwise follow this step by step written article on how to install Node.js? Once the Node is installed run below cmd to check the Node.js version: node -v # v10.16.0 Create React Application Let’s start building the React project with create-react-app (CRA). npx create-react-app react-mernstack-crud Get inside the React project folder: cd react-mernstack-crud To start the React MERN Stack project, run following command: npm start This command opens the React project on the following URL: localhost:3000 Once the React is installed successfully, then you can verify the React version in package.json file. "dependencies": { "react": "^16.9.0", "react-dom": "^16.9.0", } Now, you are all set to build the React CRUD app! Integrating React Bootstrap with React App In the next step, we will install the React Bootstrap front-end framework in our MERN stack app. This framework will allow us to use the Bootstrap’s UI component in our React CRUD app. React Bootstrap allows us to import individual UI components instead of importing the whole set of libraries. npm install react-bootstrap bootstrap Then, go to src/app.js and import the following Bootstrap CSS above App.css file. import 'bootstrap/dist/css/bootstrap.css'; You can add <link> tag in your React app’s index.html file to use the Bootstrap UI components. You can also import individual Bootstrap 4 components in your React CRUD app. Creating Simple React Components In this step, we will learn to create react components for managing data in the MERN stack CRUD application. Head over to src folder, make a folder and name it components and within that directory create the following components. create-student.component.js edit-student.component.js student-list.component.js Go to src/components/create-student.component.js and add the following code. import React, { Component } from "react"; export default class CreateStudent extends Component { render() { return ( <div> <p>React Create Student Component!</p> </div> ); } } Go to src/components/edit-student.component.js and add the following code. import React, { Component } from "react"; export default class EditStudent extends Component { render() { return ( <div> <p>React Edit Student Component!</p> </div> ); } } Go to src/components/student-list.component.js and add the following code. import React, { Component } from "react"; export default class StudentList extends Component { render() { return ( <div> <p>React Student List Component!</p> </div> ); } } Implementing React Router In this step, we will implement router in React.js app. Enter the command in terminal and hit enter to install the React Router. npm install react-router-dom --save Next, head over to src/index.js file and tie the App component with the help of <BrowserRouter> object. import React from "react"; import ReactDOM from "react-dom"; import { BrowserRouter } from "react-router-dom"; import "./index.css"; import App from "./App"; import * as serviceWorker from "./serviceWorker"; ReactDOM.render( <BrowserRouter> <App /> </BrowserRouter>, document.getElementById("root") ); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister(); Next, include the menu in our React CRUD app. Add the given below code in the src/App.js. import React from "react"; import Nav from "react-bootstrap/Nav"; import Navbar from "react-bootstrap/Navbar"; import Container from "react-bootstrap/Container"; import Row from "react-bootstrap/Row"; import Col from "react-bootstrap/Col"; import "bootstrap/dist/css/bootstrap.css"; import "./App.css"; import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom"; import CreateStudent from "./components/create-student.component"; import EditStudent from "./components/edit-student.component"; import StudentList from "./components/student-list.component"; function App() { return (<Router> <div className="App"> <header className="App-header"> <Navbar bg="dark" variant="dark"> <Container> <Navbar.Brand> <Link to={"/create-student"} className="nav-link"> React MERN Stack App </Link> </Navbar.Brand> <Nav className="justify-content-end"> <Nav> <Link to={"/create-student"} className="nav-link"> Create Student </Link> </Nav> {/* <Nav> <Link to={"/edit-student/:id"} className="nav-link"> Edit Student </Link> </Nav> */} <Nav> <Link to={"/student-list"} className="nav-link"> Student List </Link> </Nav> </Nav> </Container> </Navbar> </header> <Container> <Row> <Col md={12}> <div className="wrapper"> <Switch> <Route exact path='/' component={CreateStudent} /> <Route path="/create-student" component={CreateStudent} /> <Route path="/edit-student/:id" component={EditStudent} /> <Route path="/student-list" component={StudentList} /> </Switch> </div> </Col> </Row> </Container> </div> </Router>); } export default App; Create React Form with React Bootstrap In this step, we will build the form using React Bootstrap front-end framework for submitting the Student data in the create-student.component.js component. import React, {Component} from "react"; import Form from 'react-bootstrap/Form' import Button from 'react-bootstrap/Button'; export default class CreateStudent extends Component { render() { return (<div class="form-wrapper"> <Form> <Form.Group controlId="Name"> <Form.Label>Name</Form.Label> <Form.Control type="text"/> </Form.Group> <Form.Group controlId="Email"> <Form.Label>Email</Form.Label> <Form.Control type="email"/> </Form.Group> <Form.Group controlId="Name"> <Form.Label>Roll No</Form.Label> <Form.Control type="text"/> </Form.Group> <Button variant="danger" size="lg" block="block" type="submit"> Create Student </Button> </Form> </div>); } } Submit Forms Data in React Next, we will learn to submit the Forms data in React.js. We have already created the Student form, and need to submit student’s: Name, Email and Roll No to the database. We will start by creating the constructor inside the CreateStudent component class. Then set the initial state of the CreateStudent component by setting this.state Object. Then declare the various functions with every React form field value, so when the user inserts the data within the form input field, a state will be set accordingly. Next, we need to define the submit event, which will allow us to create new student data when the user clicks on `Create Student` submit button. import React, {Component} from "react"; import Form from 'react-bootstrap/Form' import Button from 'react-bootstrap/Button'; export default class CreateStudent extends Component { constructor(props) { super(props) // Setting up functions this.onChangeStudentName = this.onChangeStudentName.bind(this); this.onChangeStudentEmail = this.onChangeStudentEmail.bind(this); this.onChangeStudentRollno = this.onChangeStudentRollno.bind(this); this.onSubmit = this.onSubmit.bind(this); // Setting up state this.state = { name: '', email: '', rollno: '' } } onChangeStudentName(e) { this.setState({name: e.target.value}) } onChangeStudentEmail(e) { this.setState({email: e.target.value}) } onChangeStudentRollno(e) { this.setState({rollno: e.target.value}) } onSubmit(e) { e.preventDefault() console.log(`Student successfully created!`); console.log(`Name: ${this.state.name}`); console.log(`Email: ${this.state.email}`); console.log(`Roll no: ${this.state.rollno}`); this.setState({name: '', email: '', rollno: ''}) } render() { return (<div className="form-wrapper"> <Form onSubmit={this.onSubmit}> <Form.Group controlId="Name"> <Form.Label>Name</Form.Label> <Form.Control type="text" value={this.state.name} onChange={this.onChangeStudentName}/> </Form.Group> <Form.Group controlId="Email"> <Form.Label>Email</Form.Label> <Form.Control type="email" value={this.state.email} onChange={this.onChangeStudentEmail}/> </Form.Group> <Form.Group controlId="Name"> <Form.Label>Roll No</Form.Label> <Form.Control type="text" value={this.state.rollno} onChange={this.onChangeStudentRollno}/> </Form.Group> <Button variant="danger" size="lg" block="block" type="submit"> Create Student </Button> </Form> </div>); } } Build Node JS Backend for MERN Stack We will create a folder inside our React app to manage the `backend` services such as database, models, schema, routes and APIs, name this folder backend. Run command to create backend folder and get inside of it. mkdir backend && cd backend Then, we need to create a separate package.json file for managing the backend of our React CRUD demo app example. npm init Next, install the given below Node dependencies for MERN stack backend. npm install mongoose express cors body-parser NPM Detail Express It’s a robust Node.js web application framework that helps in creating powerful REST APIs. MongoDB It’s a NoSQL document-oriented database for creating a robust web application. CORS It’s a node.js package helps in enabling Access-Control-Allow-Origin CORS header. bodyParser This package extracts the entire body portion of an incoming request stream and exposes it on req.body.  Install the nodemon dependency to automate the server restarting process. npm install nodemon --save-dev Your final package.json file will look something like this. { "name": "mearn-stack-backend", "version": "1.0.0", "description": "MERN Stack backend", "main": "server.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "Digamber Rawat", "license": "ISC", "dependencies": { "body-parser": "^1.19.0", "cors": "^2.8.5", "express": "^4.17.1", "mongoose": "^5.6.9" }, "devDependencies": { "nodemon": "^1.19.1" } } Setting up MongoDB Database Next, we will set up a MongoDB database for React MERN stack app. We have already installed mongoDB, create database folder inside the backend folder and create a file by the name of db.js and paste the following code inside of it. module.exports = { db: 'mongodb://localhost:27017/reactdb' }; We have declared the mongoDB database, here 'reactdb' is the database name. Locally it doesn’t require user name and password; however, in the production, you must create an admin and assign the database to a specific user. Define Mongoose Schema Then, create a mongoDB schema for interacting with mongoDB database. Create a folder inside backend folder to keep schema related files and name it Models and create a file Student.js inside of it. mkdir Models && cd Models && touch Student.js Next, include the following code in backend/models/Student.js file: const mongoose = require('mongoose'); const Schema = mongoose.Schema; let studentSchema = new Schema({ name: { type: String }, email: { type: String }, rollno: { type: Number } }, { collection: 'students' }) module.exports = mongoose.model('Student', studentSchema) We declared a name, email and rollno fields along with their respective data types in student Schema. Create Routes Using Express/Node JS for React CRUD App In this step, we are building routes (REST APIs) for React CRUD CREATE, READ, UPDATE and DELETE app using Express and Node.js. These routes will help us to manage the data in our React MERN stack student app. Create a folder and name it routes, here we will keep all the routes related files. Also, create the student.routes.js file inside this folder in this file we will define REST APIs. mkdir routes && cd routes && touch student.route.js Then, go to backend/routes/student.route.js file and add the following code. let mongoose = require('mongoose'), express = require('express'), router = express.Router(); // Student Model let studentSchema = require('../models/Student'); // CREATE Student router.route('/create-student').post((req, res, next) => { studentSchema.create(req.body, (error, data) => { if (error) { return next(error) } else { console.log(data) res.json(data) } }) }); // READ Students router.route('/').get((req, res) => { studentSchema.find((error, data) => { if (error) { return next(error) } else { res.json(data) } }) }) // Get Single Student router.route('/edit-student/:id').get((req, res) => { studentSchema.findById(req.params.id, (error, data) => { if (error) { return next(error) } else { res.json(data) } }) }) // Update Student router.route('/update-student/:id').put((req, res, next) => { studentSchema.findByIdAndUpdate(req.params.id, { $set: req.body }, (error, data) => { if (error) { return next(error); console.log(error) } else { res.json(data) console.log('Student updated successfully !') } }) }) // Delete Student router.route('/delete-student/:id').delete((req, res, next) => { studentSchema.findByIdAndRemove(req.params.id, (error, data) => { if (error) { return next(error); } else { res.status(200).json({ msg: data }) } }) }) module.exports = router; Configure Server.js in Node/Express.js Backend We have almost created everything to set up the Node and Expresss.js backend for React 16.9.0 MERN Stack CRUD app. Now we will create the server.js file in the root of the backend folder. Run command from the root of the backend folder to create server.js file. touch server.js Paste the following code inside the backend/server.js file. let express = require('express'); let mongoose = require('mongoose'); let cors = require('cors'); let bodyParser = require('body-parser'); let dbConfig = require('./database/db'); // Express Route const studentRoute = require('../backend/routes/student.route') // Connecting mongoDB Database mongoose.Promise = global.Promise; mongoose.connect(dbConfig.db, { useNewUrlParser: true }).then(() => { console.log('Database sucessfully connected!') }, error => { console.log('Could not connect to database : ' + error) } ) const app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(cors()); app.use('/students', studentRoute) // PORT const port = process.env.PORT || 4000; const server = app.listen(port, () => { console.log('Connected to port ' + port) }) // 404 Error app.use((req, res, next) => { next(createError(404)); }); app.use(function (err, req, res, next) { console.error(err.message); if (!err.statusCode) err.statusCode = 500; res.status(err.statusCode).send(err.message); }); Now, we have created the backend for our MERN stack app. Open the terminal and run the command to start MongoDB, It will allow you to save the student data in the database. mongod Also, open another terminal and run the following command to start the Nodemon server by staying in the backend folder. nodemon server.js # [nodemon] 1.19.1 # [nodemon] to restart at any time, enter `rs` # [nodemon] watching: *.* # [nodemon] starting `node server.js` # Connected to port 4000 # Database sucessfully connected! Following will be your APIs routes created with Express.js, MongoDB and Node.js. REST API URL GET http://localhost:4000/students POST /students/create-student GET /students/edit-student/id PUT /students/update-student/id DELETE /students/delete-student/id You can also test these APIs in Postmen API development tool, click here to download Postmen. Using Axios with React to Make HTTP Request In this step, we will learn to use the Axios library in React MERN Stack app to handle the HTTP request. Axios is a promise-based HTTP client for the browser and node.js. It offers the following features. Make XMLHttpRequests from the browser Handle http requests from node.js Supports the Promise API Intercept request and response Transform request and response data Cancel requests Self-regulating for JSON data Client-side protection from XSRF Run command in the terminal to install axios in React CRUD app. npm install axios  Next, we will send the student’s data to the MongoDB server as an object using the Axios post http method. import React, { Component } from "react"; import Form from 'react-bootstrap/Form' import Button from 'react-bootstrap/Button'; import axios from 'axios'; export default class CreateStudent extends Component { constructor(props) { super(props) // Setting up functions this.onChangeStudentName = this.onChangeStudentName.bind(this); this.onChangeStudentEmail = this.onChangeStudentEmail.bind(this); this.onChangeStudentRollno = this.onChangeStudentRollno.bind(this); this.onSubmit = this.onSubmit.bind(this); // Setting up state this.state = { name: '', email: '', rollno: '' } } onChangeStudentName(e) { this.setState({ name: e.target.value }) } onChangeStudentEmail(e) { this.setState({ email: e.target.value }) } onChangeStudentRollno(e) { this.setState({ rollno: e.target.value }) } onSubmit(e) { e.preventDefault() const studentObject = { name: this.state.name, email: this.state.email, rollno: this.state.rollno }; axios.post('http://localhost:4000/students/create-student', studentObject) .then(res => console.log(res.data)); this.setState({ name: '', email: '', rollno: '' }) } render() { return (<div className="form-wrapper"> <Form onSubmit={this.onSubmit}> <Form.Group controlId="Name"> <Form.Label>Name</Form.Label> <Form.Control type="text" value={this.state.name} onChange={this.onChangeStudentName} /> </Form.Group> <Form.Group controlId="Email"> <Form.Label>Email</Form.Label> <Form.Control type="email" value={this.state.email} onChange={this.onChangeStudentEmail} /> </Form.Group> <Form.Group controlId="Name"> <Form.Label>Roll No</Form.Label> <Form.Control type="text" value={this.state.rollno} onChange={this.onChangeStudentRollno} /> </Form.Group> <Button variant="danger" size="lg" block="block" type="submit"> Create Student </Button> </Form> </div>); } }  
Laravel 5.6 - RealTime CRUD System Using Google Firebase
Today, we are share with you how to built real time CRUD system in laravel using google firebase. yes realtime insert, update, delete or listing is easily possible using google firebase database. in this article we are show to you step by step how to create google firebase database and how to integrate in your laravel application and how to built a realtime CRUD. [ADDCODE] You can do many realtime programming stuff by google firebase. after you follow all step of this article then you got final output look like following screenshot. Create New Project In Firebase: Now, we are start step by step how to built realtime CRUD system using google firebase. so, first you should create one google firebase project. if you don't know how to create google firebase project then visit our this link How to create google firebase project. After create your google firebase project you must be get following things from your created project. 1.) api_key 2.) auth_domain 3.) database_url 4.) secret 5.) Legacy server key (Only use for notification) This all things you got from your google firebase project easily Configure Google Firebase Setting: Now, we are configure google firebase setting in our laravel application. so, open config/services.php file and set following configuration in this file. 'firebase' => [ 'api_key' => 'api_key', // Only used for JS integration 'auth_domain' => 'auth_domain', // Only used for JS integration 'database_url' => 'https://database_url.com/', 'secret' => 'secret', 'storage_bucket' => '', // Only used for JS integration ], Create Route: Now, create following route in your routes/web.php file. add following route in it. Route::get('users', 'HomeController@users'); Here, we are create one get route for user display view. Add users Method in HomeController: Now, we are add one users function app/Http/Controllers/HomeController.php file. namespace App\Http\Controllers; use Illuminate\Http\Request; class HomeController extends Controller { public function users() { return view('realtimecrud'); } } Create View File: Now, we are create realtimecrud.blade.php in resources/views folder and add following bootstap code in this file for your design view. @extends('layouts.app') @section('style') <style type="text/css"> .desabled { pointer-events: none; } </style> @endsection @section('content') <div class="container"> <div class="row"> <div class="col-md-4"> <div class="card card-default"> <div class="card-header"> <div class="row"> <div class="col-md-10"> <strong>Add User</strong> </div> </div> </div> <div class="card-body"> <form id="addUser" class="" method="POST" action=""> <div class="form-group"> <label for="first_name" class="col-md-12 col-form-label">First Name</label> <div class="col-md-12"> <input id="first_name" type="text" class="form-control" name="first_name" value="" required autofocus> </div> </div> <div class="form-group"> <label for="last_name" class="col-md-12 col-form-label">Last Name</label> <div class="col-md-12"> <input id="last_name" type="text" class="form-control" name="last_name" value="" required autofocus> </div> </div> <div class="form-group"> <div class="col-md-12 col-md-offset-3"> <button type="button" class="btn btn-primary btn-block desabled" id="submitUser"> Submit </button> </div> </div> </form> </div> </div> </div> <div class="col-md-8"> <div class="card card-default"> <div class="card-header"> <div class="row"> <div class="col-md-10"> <strong>All Users Listing</strong> </div> </div> </div> <div class="card-body"> <table class="table table-bordered"> <tr> <th>First Name</th> <th>Last Name</th> <th width="180" class="text-center">Action</th> </tr> <tbody id="tbody"> </tbody> </table> </div> </div> </div> </div> </div> <!-- Delete Model --> <form action="" method="POST" class="users-remove-record-model"> <div id="remove-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="custom-width-modalLabel" aria-hidden="true" style="display: none;"> <div class="modal-dialog" style="width:55%;"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="custom-width-modalLabel">Delete Record</h4> <button type="button" class="close remove-data-from-delete-form" data-dismiss="modal" aria-hidden="true">×</button> </div> <div class="modal-body"> <h4>You Want You Sure Delete This Record?</h4> </div> <div class="modal-footer"> <button type="button" class="btn btn-default waves-effect remove-data-from-delete-form" data-dismiss="modal">Close</button> <button type="button" class="btn btn-danger waves-effect waves-light deleteMatchRecord">Delete</button> </div> </div> </div> </div> </form> <!-- Update Model --> <form action="" method="POST" class="users-update-record-model form-horizontal"> <div id="update-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="custom-width-modalLabel" aria-hidden="true" style="display: none;"> <div class="modal-dialog" style="width:55%;"> <div class="modal-content" style="overflow: hidden;"> <div class="modal-header"> <h4 class="modal-title" id="custom-width-modalLabel">Update Record</h4> <button type="button" class="close update-data-from-delete-form" data-dismiss="modal" aria-hidden="true">×</button> </div> <div class="modal-body" id="updateBody"> </div> <div class="modal-footer"> <button type="button" class="btn btn-default waves-effect update-data-from-delete-form" data-dismiss="modal">Close</button> <button type="button" class="btn btn-success waves-effect waves-light updateUserRecord">Update</button> </div> </div> </div> </div> </form> @endsection After add this simple html code in your blade file but still it is not done. now we are add some google firebase javascript code for built realtime CRUD. so, now add following js code in this file into the bottom <script src="https://www.gstatic.com/firebasejs/4.9.1/firebase.js"></script> <script> // Initialize Firebase var config = { apiKey: "{{ config('services.firebase.api_key') }}", authDomain: "{{ config('services.firebase.auth_domain') }}", databaseURL: "{{ config('services.firebase.database_url') }}", storageBucket: "{{ config('services.firebase.storage_bucket') }}", }; firebase.initializeApp(config); var database = firebase.database(); var lastIndex = 0; // Get Data firebase.database().ref('users/').on('value', function(snapshot) { var value = snapshot.val(); var htmls = []; $.each(value, function(index, value){ if(value) { htmls.push('<tr>\ <td>'+ value.first_name +'</td>\ <td>'+ value.last_name +'</td>\ <td><a data-toggle="modal" data-target="#update-modal" class="btn btn-outline-success updateData" data-id="'+index+'">Update</a>\ <a data-toggle="modal" data-target="#remove-modal" class="btn btn-outline-danger removeData" data-id="'+index+'">Delete</a></td>\ </tr>'); } lastIndex = index; }); $('#tbody').html(htmls); $("#submitUser").removeClass('desabled'); }); // Add Data $('#submitUser').on('click', function(){ var values = $("#addUser").serializeArray(); var first_name = values[0].value; var last_name = values[1].value; var userID = lastIndex+1; firebase.database().ref('users/' + userID).set({ first_name: first_name, last_name: last_name, }); // Reassign lastID value lastIndex = userID; $("#addUser input").val(""); }); // Update Data var updateID = 0; $('body').on('click', '.updateData', function() { updateID = $(this).attr('data-id'); firebase.database().ref('users/' + updateID).on('value', function(snapshot) { var values = snapshot.val(); var updateData = '<div class="form-group">\ <label for="first_name" class="col-md-12 col-form-label">First Name</label>\ <div class="col-md-12">\ <input id="first_name" type="text" class="form-control" name="first_name" value="'+values.first_name+'" required autofocus>\ </div>\ </div>\ <div class="form-group">\ <label for="last_name" class="col-md-12 col-form-label">Last Name</label>\ <div class="col-md-12">\ <input id="last_name" type="text" class="form-control" name="last_name" value="'+values.last_name+'" required autofocus>\ </div>\ </div>'; $('#updateBody').html(updateData); }); }); $('.updateUserRecord').on('click', function() { var values = $(".users-update-record-model").serializeArray(); var postData = { first_name : values[0].value, last_name : values[1].value, }; var updates = {}; updates['/users/' + updateID] = postData; firebase.database().ref().update(updates); $("#update-modal").modal('hide'); }); // Remove Data $("body").on('click', '.removeData', function() { var id = $(this).attr('data-id'); $('body').find('.users-remove-record-model').append('<input name="id" type="hidden" value="'+ id +'">'); }); $('.deleteMatchRecord').on('click', function(){ var values = $(".users-remove-record-model").serializeArray(); var id = values[0].value; firebase.database().ref('users/' + id).remove(); $('body').find('.users-remove-record-model').find( "input" ).remove(); $("#remove-modal").modal('hide'); }); $('.remove-data-from-delete-form').click(function() { $('body').find('.users-remove-record-model').find( "input" ).remove(); }); </script> After add this javascript code in your blade file then your realtime crud system done successfully. Now we are ready to run our example so run bellow command ro quick run: php artisan serve Now you can open bellow URL on your browser: http://localhost:8000/users Please also check our demo for realtime CRUD system. We are hope you like this tutorials, if any question regarding any query please post your question in our forums click on bellow link Laravelcode's Forums
Laravel 5.5 - simple crud operation with example
Today, we are sharing how to make simple laravel CRUD(insert, update, delete or listing) operations with example. Every new laravel developer need to start learning laravel with some simple CRUD because they are very fundamentals of any laravel application. We will guide you how to make simple crud in laravel step by step. We are starting with how to create laravel new project in your system how to set database setting etc... in this tutorials. There are many laravel crud generator package is available on github but this is no meaning if you are not know how is work. You can only get to know this logic if you know how to work on laravel crud manualy. So, in this post you will learn step by step all crud operation like record listing, record inserting, record updating or editing and record deleted with confirm alert box. Simply follow each and every step and make laravel crud easily. [ADDCODE] In this tutorial we are making CRUD for tips table. After all these steps, your output will look like this. Create Laravel Project: First, we need to create fresh laravel application by runing following command in your terminal. composer create-project --prefer-dist laravel/laravel your_project_name Configure .env file: After creating a laravel project, open your project in your any editor and open .env file and configure your database setting in .env change following value in that file like that DB_DATABASE=databasename DB_USERNAME=phpmyadminusername DB_PASSWORD=phpmyadminpassword Make Laravel Auth: Next, we are create laravel bydefault authentication by run following command. laravel provide ready made authentication system so we are use that. php artisan make:auth Create Route: Now, open your routes/web.php file and add one route recource in this file for our tips crud. here i am use resource instade of all saperate route. Route::resource('tips', 'TipsController'); Simple add above line in your web.php file Change in app.blade.php file: Next, we are change some in resources/views/layouts/app.blade.php file so, open this file and simply copy this all code and past in your app.blade.php file. <!DOCTYPE html> <html lang="{{ app()->getLocale() }}"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- CSRF Token --> <meta name="csrf-token" content="{{ csrf_token() }}"> <title>{{ config('app.name', 'Laravel') }}</title> <!-- Styles --> <link href="{{ asset('css/app.css') }}" rel="stylesheet"> <script type="text/javascript"> var current_page_url = "<?php echo URL::current(); ?>"; var current_page_fullurl = "<?php echo URL::full(); ?>"; var CSRF_TOKEN='{{ csrf_token() }}'; </script> </head> <body> <div id="app"> <nav class="navbar navbar-default navbar-static-top"> <div class="container"> <div class="navbar-header"> <!-- Collapsed Hamburger --> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#app-navbar-collapse" aria-expanded="false"> <span class="sr-only">Toggle Navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <!-- Branding Image --> <a class="navbar-brand" href="{{ url('/home') }}"> CBTF </a> </div> <div class="collapse navbar-collapse" id="app-navbar-collapse"> <!-- Left Side Of Navbar --> <ul class="nav navbar-nav">   </ul> <!-- Right Side Of Navbar --> <ul class="nav navbar-nav navbar-right"> <!-- Authentication Links --> @guest <li><a href="{{ route('login') }}">Login</a></li> <li><a href="{{ route('register') }}">Register</a></li> @else <li><a href="{{ URL::route('tips.index') }}">Tips</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false" aria-haspopup="true"> {{ Auth::user()->name }} <span class="caret"></span> </a> <ul class="dropdown-menu"> <li> <a href="{{ route('logout') }}" onclick="event.preventDefault(); document.getElementById('logout-form').submit();"> Logout </a> <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;"> {{ csrf_field() }} </form> </li> </ul> </li> @endguest </ul> </div> </div> </nav> <div class="container"> <div class="row"> <div class="col-md-10 col-md-offset-1"> @include('alert') </div> </div> </div> @yield('content') </div> @include('deleteModel') <!-- Scripts --> <script src="{{ asset('js/app.js') }}"></script> <script src="{{ asset('js/custom.js') }}"></script> </body> </html> Create deleteModel.blade.php file: Now, create deleteModel.blade.php file for delete confurm model on this path resources/views <form action="" method="POST" class="remove-record-model"> <div id="custom-width-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="custom-width-modalLabel" aria-hidden="true" style="display: none;"> <div class="modal-dialog" style="width:55%;"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h4 class="modal-title" id="custom-width-modalLabel">Delete Record</h4> </div> <div class="modal-body"> <h4>You Want You Sure Delete This Record?</h4> </div> <div class="modal-footer"> <button type="button" class="btn btn-default waves-effect remove-data-from-delete-form" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-danger waves-effect waves-light">Delete</button> </div> </div> </div> </div> </form> Create alert.blade.php file: Now, create alert.blade.php file in this path resources/views we are create this file for all alert like when we are insert data and display success message and failed message or any warning message. @if ($errors->any()) <div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">×</span> </button> <strong>Error Alert!</strong> Please check the form below for errors </div> @endif @if ($message = Session::get('success')) <div class="alert alert-success alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">×</span> </button> <strong>Success Alert!</strong> <?php echo $message; ?> </div> <?php Session::forget('success');?> @endif @if ($message = Session::get('error')) <div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">×</span> </button> <strong>Error Alert!</strong> <?php echo $message; ?> </div> <?php Session::forget('error');?> @endif @if ($message = Session::get('warning')) <div class="alert alert-warning alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">×</span> </button> <strong>Waarning Alert!</strong> <?php echo $message; ?> </div> <?php Session::forget('warning');?> @endif @if ($message = Session::get('info')) <div class="alert alert-indo alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">×</span> </button> <strong>Information Alert!</strong> <?php echo $message; ?> </div> <?php Session::forget('info');?> @endif Create custom.js File: Now, we are create custom.js file on this path public/js and in this file we are write js code for out delete confirm model. this js logic you can use any your laravel application for delete records with confirmation model. $(document).ready(function(){ // For A Delete Record Popup $('.remove-record').click(function() { var id = $(this).attr('data-id'); var url = $(this).attr('data-url'); var token = CSRF_TOKEN; $(".remove-record-model").attr("action",url); $('body').find('.remove-record-model').append('<input name="_token" type="hidden" value="'+ token +'">'); $('body').find('.remove-record-model').append('<input name="_method" type="hidden" value="DELETE">'); $('body').find('.remove-record-model').append('<input name="id" type="hidden" value="'+ id +'">'); }); $('.remove-data-from-delete-form').click(function() { $('body').find('.remove-record-model').find( "input" ).remove(); }); $('.modal').click(function() { // $('body').find('.remove-record-model').find( "input" ).remove(); }); }); Create tips Table Migration: Now, we are create tips table migration by run following command in terminal. php artisan make:migration create_tips_tbl After runing this command in your terminal then one mingration file automatic generated in your this path database/migrations/ then here your show one new migration file so, open it and change like thai in this file. use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateTipsTbl extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('tips', function (Blueprint $table) { $table->increments('id'); $table->string('title')->nullble(); $table->text('tips')->nullble(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('tips'); } } After change in this migration file then run this migration by following command in your terminal. php artisan migrate After run this command then your tips table automatic generated in database. Create tips Table Model: Now, create tips table model in following path app/Tip.php and add following code in this file. namespace App; use Illuminate\Database\Eloquent\Model; class Tip extends Model { protected $table = 'tips'; protected $guarded = array(); public function getData() { return static::orderBy('id', 'desc')->paginate(5); } public function AddData($input) { return static::create($input); } public function findData($id) { return static::find($id); } public function updateData($id, $input) { return static::where('id', $id)->update($input); } public function destroyData($id) { return static::where('id',$id)->delete(); } } Create TipsController: Now, create TipsController.php file in this path app/Http/Controllers and simple copy this following code in this file. namespace App\Http\Controllers; use App\Http\Requests; use Illuminate\Http\Request; use App\Tip; class TipsController extends HomeController { public function __construct() { parent::__construct(); $this->Tip = new Tip; $this->moduleTitleS = 'Tips'; $this->moduleTitleP = 'Tips'; view()->share('moduleTitleP',$this->moduleTitleP); view()->share('moduleTitleS',$this->moduleTitleS); } public function index() { $data = $this->Tip->getData(); return view($this->moduleTitleP.'.index',compact('data')) ->with('i',0); } public function create() { return view($this->moduleTitleP.'.create'); } public function store(Request $request) { $this->validate($request, [ 'title' => 'required|max:255', 'tips' => 'required', ]); $input = array_except($request->all(),array('_token')); $this->Tip->AddData($input); \Session::put('success','Tip Store Successfully!!'); return redirect()->route('tips.index'); } public function edit($id) { $data = $this->Tip->findData($id); return view($this->moduleTitleP.'.edit',compact('data')); } public function update(Request $request, $id) { $this->validate($request, [ 'title' => 'required|max:255', 'tips' => 'required', ]); $input = array_except($request->all(),array('_token', '_method')); $this->Tip->updateData($id, $input); \Session::put('success','Tip Updated Successfully!!'); return redirect()->route('tips.index'); } public function destroy($id) { $this->Tip->destroyData($id); \Session::put('success','Post Delete Successfully!!'); return redirect()->route('tips.index'); } } Create All View Blade File: Now, we are create all following blade file one by one 1.)index.blade.php 2.)create.blade.php 3.)edit.blade.php resources/views/Tips/index.blade.php File: Now, create this file and simply copy and path following code in this file for all tips listing. @extends('layouts.app') @section('content') <div class="container"> <div class="row"> <div class="col-md-10 col-md-offset-1"> <div class="panel panel-default"> <div class="panel-heading"> <div class="row"> <div class="col-md-10"> <strong>All Tips Listing</strong> </div> <div class="col-md-2"> <a href="{{ URL::route('tips.create') }}" class="btn btn-info pull-right">Add Tips</a> </div> </div> </div> <div class="panel-body"> <table class="table table-bordered"> <tr> <th>Title</th> <th width="500">Tips Description</th> <th width="180" class="text-center">Action</th> </tr> @if(!empty($data) && $data->count()) @foreach($data as $key => $value) <tr> <td>{{ $value->title }}</td> <td> @if (strlen($value->tips) > 100) {!! substr(strip_tags(html_entity_decode($value->tips)), 0, 100) . '.....' !!} @else {!! strip_tags($value->tips) !!} @endif </td> <td class="text-center"> <a href="{!! URL::route('tips.edit', $value->id) !!}" class="btn btn-success">Edit</a> <a data-toggle="modal" data-url="{!! URL::route('tips.destroy', $value->id) !!}" data-id="{{$value->id}}" data-target="#custom-width-modal" class="btn btn-danger remove-record">Delete</a> </td> </tr> @endforeach @endif </table> </div> </div> {!! $data->appends([])->render() !!} </div> </div> </div> @endsection resources/views/Tips/create.blade.php File: Now, create this file for create and insert tips records in our database. simply copy this all following code and path in your this file. @extends('layouts.app') @section('content') <div class="container"> <div class="row"> <div class="col-md-10 col-md-offset-1"> <div class="panel panel-default"> <div class="panel-heading">Create Tip</div> <div class="panel-body"> <form class="form-horizontal" method="POST" action="{{ route('tips.store') }}"> {{ csrf_field() }} <div class="form-group{{ $errors->has('title') ? ' has-error' : '' }}"> <label for="title" class="col-md-3 control-label">Title</label> <div class="col-md-7"> <input id="title" type="text" class="form-control" name="title" value="{{ old('title') }}" required autofocus> @if ($errors->has('title')) <span class="help-block"> <strong>{{ $errors->first('title') }}</strong> </span> @endif </div> </div> <div class="form-group{{ $errors->has('tips') ? ' has-error' : '' }}"> <label for="tips" class="col-md-3 control-label">Tips Description</label> <div class="col-md-7"> <textarea id="tips" rows="6" class="form-control" name="tips" required>{{ old('tips') }}</textarea> @if ($errors->has('tips')) <span class="help-block"> <strong>{{ $errors->first('tips') }}</strong> </span> @endif </div> </div> <div class="form-group"> <div class="col-md-7 col-md-offset-3"> <button type="submit" class="btn btn-primary btn-block"> Submit </button> </div> </div> </form> </div> </div> </div> </div> </div> @endsection resources/views/Tips/edit.blade.php Now, we are create edit file for update any record in our database. this code like that @extends('layouts.app') @section('content') <div class="container"> <div class="row"> <div class="col-md-10 col-md-offset-1"> <div class="panel panel-default"> <div class="panel-heading">Edit Tip</div> <div class="panel-body"> {{ Form::model($data, ['route' => ['tips.update', $data->id], 'method' => 'patch', 'class' =>'form-horizontal']) }} <div class="form-group{{ $errors->has('title') ? ' has-error' : '' }}"> <label for="title" class="col-md-3 control-label">Title</label> <div class="col-md-7"> <input id="title" type="text" class="form-control" name="title" value="{{ $data->title }}" required autofocus> @if ($errors->has('title')) <span class="help-block"> <strong>{{ $errors->first('title') }}</strong> </span> @endif </div> </div> <div class="form-group{{ $errors->has('tips') ? ' has-error' : '' }}"> <label for="tips" class="col-md-3 control-label">Tips Description</label> <div class="col-md-7"> <textarea id="tips" rows="6" class="form-control" name="tips" required>{{ $data->tips }}</textarea> @if ($errors->has('tips')) <span class="help-block"> <strong>{{ $errors->first('tips') }}</strong> </span> @endif </div> </div> <div class="form-group"> <div class="col-md-7 col-md-offset-3"> <button type="submit" class="btn btn-primary btn-block"> Update </button> </div> </div> {{ Form::close() }} </div> </div> </div> </div> </div> @endsection Now we are ready to run our example so run bellow command ro quick run: php artisan serve Now you can test one by one route url in your browser like that: http://localhost:8000/tips We are hope you like this tutorials, if any question regarding any query please post your question in our forums click on bellow link Laravelcode's Forums
Laravel 5.5 - VueJS 2.0 CRUD Operations
Today, we are share with you VueJS 2.0 CRUD (insert, update, delete and listing) oparation in laravel 5.5, we all are known laravel 5.5 and VueJS 2.0 is best combination for development any web application. in this article we are show you how to make laravel 5.5 and VueJS 2.0 crud in step by step don't warry if you are beginner, intermediate or expert in laravel or VueJS. simply follow this all step any easyly make VueJS 2.0 CRUD with laravel 5.5 Before starting vuejs crud with laravel you required following things in your system. Development Server Requirements: PHP >= 7.0.0 OpenSSL PHP Extension PDO PHP Extension Mbstring PHP Extension Tokenizer PHP Extension XML PHP Extension Apache/Nginx MySQl Composer NodeJs with NPM Step : 1 Create Laravel Project: First, we need to create one laravel fresh project using composer. simply run following command in your terminal for create new laravel project. composer create-project --prefer-dist laravel/laravel ProjectName Step : 2 Configure .env Next, after create laravel project open .env file and configure your database setting like that. DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=YOUR-DATABASE-NAME DB_USERNAME=DATABASE-USERNAME DB_PASSWORD=DATABASE-USER-PASSWORD Step : 3 Create Post Table Migration: Next, we are create one post table migration for make all crud oparation on it. simple run following command and create migration file. php artisan make:migration create_post_table --create=posts After create migration open migration file and make change in it like that. use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreatePostTable 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'); } } Then run migration using following command. php artisan migrate Step : 4 Create Post Table Model And Controller: Next, we are create Post table model and controller run by following command. php artisan make:model Post -r You can locate the model at /app/Post.php and controller at /app/Http/Controllers/PostController.php Next, open your model app/Post.php file and make following change. namespace App; use Illuminate\Database\Eloquent\Model; class Post extends Model { protected $fillable = [ 'title', 'description', ]; } app/Http/Controllers/PostController.php namespace App\Http\Controllers; use App\Post; use Illuminate\Http\Request; class PostController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $posts = Post::get(); return response()->json([ 'posts' => $posts, ], 200); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $this->validate($request, [ 'title' => 'required|max:255', 'description' => 'required', ]); $post = Post::create([ 'title' => request('title'), 'description' => request('description'), ]); return response()->json([ 'post' => $post, 'message' => 'Success' ], 200); } /** * Display the specified resource. * * @param \App\Post $post * @return \Illuminate\Http\Response */ public function show(Post $post) { // } /** * Show the form for editing the specified resource. * * @param \App\Post $post * @return \Illuminate\Http\Response */ public function edit(Post $post) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Post $post * @return \Illuminate\Http\Response */ public function update(Request $request, Post $post) { $this->validate($request, [ 'title' => 'required|max:255', 'description' => 'required', ]); $post->title = request('title'); $post->description = request('description'); $post->save(); return response()->json([ 'message' => 'Post updated successfully!' ], 200); } /** * Remove the specified resource from storage. * * @param \App\Post $post * @return \Illuminate\Http\Response */ public function destroy(Post $post) { // } } Step : 5 Create Post Route: Next, we need to create insert, update, index, delete, create routes for this crud. we are make crud so resource route is best. i hope you all are very well known resource Route. Route::resource('/posts', 'PostController'); Step : 6 Register Vue Component: Next, we are need to register vuejs component in /resources/assets/js/app.js file open it and make following changes /** * First we will load all of this project's JavaScript dependencies which * includes Vue and other libraries. It is a great starting point when * building robust, powerful web applications using Vue and Laravel. */ require('./bootstrap'); window.Vue = require('vue'); /** * Next, we will create a fresh Vue application instance and attach it to * the page. Then, you may begin adding components to this application * or customize the JavaScript scaffolding to fit your unique needs. */ Vue.component('example', require('./components/Example.vue')); Vue.component('posts', require('./components/Post.vue')); const app = new Vue({ el: '#app' }); After add component open your /resources/views/home.blade.php file and make following changes @extends('layouts.app') @section('content') <posts></posts> @endsection Step : 7 Create New VueJS Component: Next, we are use here vue js 2.0 for front. and we all are known laravel provide bydefault setting for vue js for easy to develope front layout. Here, we are create one vue js component file Post.vue in /resources/assets/js/components/ folder [ADDCODE] <template> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="panel panel-default"> <div class="panel-heading">My Post</div> <div class="panel-body"> </div> </div> </div> </div> </div> </template> <template> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="panel panel-default"> <div class="panel-heading"> <button @click="initAddPost()" class="btn btn-primary btn-xs pull-right"> + Add New Post </button> My Post </div> <div class="panel-body"> <table class="table table-bordered table-striped table-responsive" v-if="posts.length > 0"> <tbody> <tr> <th> No. </th> <th> Title </th> <th> Description </th> <th> Action </th> </tr> <tr v-for="(posts, index) in posts"> <td>{{ index + 1 }}</td> <td> {{ posts.title }} </td> <td> {{ posts.description }} </td> <td> <button @click="initUpdate(index)" class="btn btn-success btn-xs">Edit</button> <button @click="deletePost(index)" class="btn btn-danger btn-xs">Delete</button> </td> </tr> </tbody> </table> </div> </div> </div> </div> <div class="modal fade" tabindex="-1" role="dialog" id="add_post_model"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button> <h4 class="modal-title">Add New Post</h4> </div> <div class="modal-body"> <div class="alert alert-danger" v-if="errors.length > 0"> <ul> <li v-for="error in errors">{{ error }}</li> </ul> </div> <div class="form-group"> <label for="title">Title:</label> <input type="text" name="title" id="title" placeholder="Title Name" class="form-control" v-model="posts.title"> </div> <div class="form-group"> <label for="description">Description:</label> <textarea name="description" id="description" cols="30" rows="5" class="form-control" placeholder="Post Description" v-model="posts.description"></textarea> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="button" @click="createPost" class="btn btn-primary">Submit</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal --> <div class="modal fade" tabindex="-1" role="dialog" id="update_post_model"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button> <h4 class="modal-title">Update Post</h4> </div> <div class="modal-body"> <div class="alert alert-danger" v-if="errors.length > 0"> <ul> <li v-for="error in errors">{{ error }}</li> </ul> </div> <div class="form-group"> <label>Title:</label> <input type="text" placeholder="Title" class="form-control" v-model="update_post.title"> </div> <div class="form-group"> <label for="description">Description:</label> <textarea cols="30" rows="5" class="form-control" placeholder="Task Description" v-model="update_post.description"></textarea> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="button" @click="updatePost" class="btn btn-primary">Submit</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal --> </div> </template> <script> export default { data(){ return { posts: { title: '', description: '' }, errors: [], posts: [], update_post: {} } }, mounted() { this.readPosts(); }, methods: { initAddPost() { this.errors = []; $("#add_post_model").modal("show"); }, createPost() { axios.post('/posts', { title: this.posts.title, description: this.posts.description, }) .then(response => { this.reset(); $("#add_post_model").modal("hide"); }) .catch(error => { this.errors = []; if (error.response.data.errors.title) { this.errors.push(error.response.data.errors.title[0]); } if (error.response.data.errors.description) { this.errors.push(error.response.data.errors.description[0]); } }); }, reset() { this.posts.title = ''; this.posts.description = ''; }, readPosts() { axios.get('/posts') .then(response => { this.posts = response.data.posts; }); }, initUpdate(index) { this.errors = []; $("#update_post_model").modal("show"); this.update_post = this.posts[index]; }, updatePost() { axios.patch('/posts/' + this.update_post.id, { title: this.update_post.title, description: this.update_post.description, }) .then(response => { $("#update_post_model").modal("hide"); }) .catch(error => { this.errors = []; if (error.response.data.errors.title) { this.errors.push(error.response.data.errors.title[0]); } if (error.response.data.errors.description) { this.errors.push(error.response.data.errors.description[0]); } }); }, deletePost(index) { let conf = confirm("Do you ready want to delete this post?"); if (conf === true) { axios.delete('/posts/' + this.posts[index].id) .then(response => { this.posts.splice(index, 1); }) .catch(error => { }); } } } } </script> Step : 8 How To Run: Our crud oparation run now how to run it. please simple follow this step. run following command for install npm dependancy npm install Now run following command for deploy nmp setup and Compile Assets and Use Post Controller: npm run dev Now we are ready to run our example so run bellow command ro quick run: php artisan serve Now you can open bellow URL on your browser: http://localhost:8000/ Now, register new user and you see your VueJS crud If you want to any problem then please write comment and also suggest for new topic for make tutorials in future. Thanks...