Search

Google Firebase's Tags

Google Firebase Push Notification in Laravel
Today our leading topic is laravel firebase push notification example. i would relish apportioning with you laravel firebase web push notification. This tutorial will give you a simple example of laravel send push notification firebase. let’s discuss send a firebase push notification utilizing laravel. follow bellow step for firebase push notification laravel. Today, i will give you simple example of send a firebase push notification utilizing laravel. you can withal use in laravel 6, laravel 7 and laravel 8 version. Firebase provides a realtime database and backend as an accommodation. The accommodation provides application developers an API that sanctions application data to be synchronized across clients and stored on Firebase’s cloud. firebase push notification is a free open source and you can facilely implement utilizing your google account. here i will give you simple to getting contrivance token of authenticated in users and then we will send web push notification. so let's simply follow bellow step to engender push notification with laravel app. Step 1: Create Firebase Project and App In first step, we have to go Firebase Console and create a project. then you have to create web app on that project as like i added bellow screenshot: After given name and next then you will received firebase sdk as like bellow screen shot: You have to save that all information because we will use in our app. Step 2: Install Laravel first of all we need to get fresh Laravel application using bellow command, So open your terminal OR command prompt and run bellow command: composer create-project --prefer-dist laravel/laravel blogFirebase Step 3: Create Auth using scaffold Now, in this step, we will create auth scaffold command to create login, register and dashboard. so run following commands: Laravel UI Package composer require laravel/ui Generate auth php artisan ui bootstrap --auth npm install npm run dev Step 4: Create Migration and Update Model In this step, we need to add new row "device_token" in users table and model. than we need to create new migration. so let's create new migration by following command. php artisan make:migration add_column_device_token database/migrations/2020_10_23_144523_add_column_device_token.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class AddColumnDeviceToken extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('users', function (Blueprint $table) { $table->string('device_token')->nullable(); }); } /** * Reverse the migrations. * * @return void */ public function down() { } } app/Models/User.php <?php namespace App\Models; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; class User extends Authenticatable { use HasFactory, Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', 'device_token' ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'email_verified_at' => 'datetime', ]; } Now we need to run a migration. so let's run bellow command: php artisan migrate Step 5: Create Route Here, we need to add some routes to store token and send push notification so let's add that route in web.php file. routes/web.php <?php use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('welcome'); }); Auth::routes(); Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home'); Route::post('/save-token', [App\Http\Controllers\HomeController::class, 'saveToken'])->name('save-token'); Route::post('/send-notification', [App\Http\Controllers\HomeController::class, 'sendNotification'])->name('send.notification'); Step 6: Add Method on Controller Here, we need add saveToken() and sendNotification() method for admin route in HomeController. In this controller there is a $SERVER_API_KEY variable where you have to get server key from firebase console setting page as like bellow screenshot: now, so let's add like as bellow: app/Http/Controllers/HomeController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; class HomeController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Show the application dashboard. * * @return \Illuminate\Contracts\Support\Renderable */ public function index() { return view('home'); } /** * Write code on Method * * @return response() */ public function saveToken(Request $request) { auth()->user()->update(['device_token'=>$request->token]); return response()->json(['token saved successfully.']); } /** * Write code on Method * * @return response() */ public function sendNotification(Request $request) { $firebaseToken = User::whereNotNull('device_token')->pluck('device_token')->all(); $SERVER_API_KEY = 'XXXXXX'; $data = [ "registration_ids" => $firebaseToken, "notification" => [ "title" => $request->title, "body" => $request->body, ] ]; $dataString = json_encode($data); $headers = [ 'Authorization: key=' . $SERVER_API_KEY, 'Content-Type: application/json', ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send'); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString); $response = curl_exec($ch); dd($response); } } Step 7: Update Blade File In this step, we need to update home.blade.php file where you have to write code for send notification and allow notification button. When you click on that button that browser popup will open with allow option and you have to allow it. so let's change it. resources/views/home.blade.php @extends('layouts.app') @section('content') <div class="container"> <div class="row justify-content-center"> <div class="col-md-8"> <center> <button id="btn-nft-enable" onclick="initFirebaseMessagingRegistration()" class="btn btn-danger btn-xs btn-flat">Allow for Notification</button> </center> <div class="card"> <div class="card-header">{{ __('Dashboard') }}</div> <div class="card-body"> @if (session('status')) <div class="alert alert-success" role="alert"> {{ session('status') }} </div> @endif <form action="{{ route('send.notification') }}" method="POST"> @csrf <div class="form-group"> <label>Title</label> <input type="text" class="form-control" name="title"> </div> <div class="form-group"> <label>Body</label> <textarea class="form-control" name="body"></textarea> </div> <button type="submit" class="btn btn-primary">Send Notification</button> </form> </div> </div> </div> </div> </div> <script src="https://www.gstatic.com/firebasejs/7.23.0/firebase.js"></script> <script> var firebaseConfig = { apiKey: "XXXX", authDomain: "XXXX.firebaseapp.com", databaseURL: "https://XXXX.firebaseio.com", projectId: "XXXX", storageBucket: "XXXX", messagingSenderId: "XXXX", appId: "XXXX", measurementId: "XXX" }; firebase.initializeApp(firebaseConfig); const messaging = firebase.messaging(); function initFirebaseMessagingRegistration() { messaging .requestPermission() .then(function () { return messaging.getToken() }) .then(function(token) { console.log(token); $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $.ajax({ url: '{{ route("save-token") }}', type: 'POST', data: { token: token }, dataType: 'JSON', success: function (response) { alert('Token saved successfully.'); }, error: function (err) { console.log('User Chat Token Error'+ err); }, }); }).catch(function (err) { console.log('User Chat Token Error'+ err); }); } messaging.onMessage(function(payload) { const noteTitle = payload.notification.title; const noteOptions = { body: payload.notification.body, icon: payload.notification.icon, }; new Notification(noteTitle, noteOptions); }); </script> @endsection Step 8: Create firebase-messaging-sw.js File In this step, we have to create firebase-messaging-sw.js in public folder and put bellow code. public/firebase-messaging-sw.js /* Give the service worker access to Firebase Messaging. Note that you can only use Firebase Messaging here, other Firebase libraries are not available in the service worker. */ importScripts('https://www.gstatic.com/firebasejs/7.23.0/firebase-app.js'); importScripts('https://www.gstatic.com/firebasejs/7.23.0/firebase-messaging.js'); /* Initialize the Firebase app in the service worker by passing in the messagingSenderId. * New configuration for app@pulseservice.com */ firebase.initializeApp({ apiKey: "XXXX", authDomain: "XXXX.firebaseapp.com", databaseURL: "https://XXXX.firebaseio.com", projectId: "XXXX", storageBucket: "XXXX", messagingSenderId: "XXXX", appId: "XXXX", measurementId: "XXX" }); /* Retrieve an instance of Firebase Messaging so that it can handle background messages. */ const messaging = firebase.messaging(); messaging.setBackgroundMessageHandler(function(payload) { console.log( "[firebase-messaging-sw.js] Received background message ", payload, ); /* Customize notification here */ const notificationTitle = "Background Message Title"; const notificationOptions = { body: "Background Message body.", icon: "/itwonders-web-logo.png", }; return self.registration.showNotification( notificationTitle, notificationOptions, ); }); Ok, now we are ready to run. So let's run project using this command: php artisan serve You can login and then allow push notification to click on button. then send notification from given form. I hope it can help you.
Laravel 8 Firebase Phone Number OTP Authentication
Laravel 8 mobile number OTP authentication article; throughout this one by one article, you will find out a way to create phone or mobile number OTP authentication in Laravel 8 using the Firebase phone sign-in auth provider. Firebase is a profound backend as a provider tool, which makes the improvement work exorbitantly facile. To develop the robust authentication system, it gives heaps of ready-made features that you could implement to your app and extend the development work. In this article, we are integrating the Firebase phone and mobile OTP authentication in the Laravel app. To integrate Firebase mobile number OTP auth in Laravel 8 app, you want to setup a simple laravel app, connect it to the database, create a controller and bind it to the route. lastly, create a easy view for sending mobile number otp through the Firebase environment. Laravel 8 Phone Number OTP Authentication using Firebase Tutorial let's Strat With Simple Step... Step 1: Install Laravel App Step 2: Create Firebase Project Step 3: Enable Firebase Phone Auth Step 4: Add Database Details Step 5: Create Controller Step 6: Add Route Step 7: Set Up Blade View Step 8: Start Development Server Step 1: Install Laravel App You need to commence the fundamental step by installing a new laravel application using composer command, ensure to configure composer on the system, then execute the following command. composer create-project --prefer-dist laravel/laravel laravel-phone-otp-auth Step 2: Create Firebase Project Visit to Firebase site, then signin using your firebase credentials, thereafter click on Create a project button. Add project name, and click on continue. Next, add Firebase to your app, so to get credentials to click on the markup icon. Next, you need to register app and click on Next. From this page, you need to copy firebase configurations. Step 3: Enable Firebase Phone Auth The Firebase project has been created. Now you have to enable the firebase phone authentication, click on the authentication tab, select the Sign-in method segment, click on the Phone item and enable the Phone auth. Step 4: Add Database Details Add database name, user name, and password into the .env file... .env DB_CONNECTION=mysql DB_HOST=localhost DB_PORT=3306 DB_DATABASE=database_px DB_USERNAME=root DB_PASSWORD= Step 5: Create Controller Open terminal, type command, then execute the command that generates a new controller; in this controller we will call the blade view for showing the mobile otp auth form. php artisan make:controller PhoneAuthController Open and add code in app/http/controllers/PhoneAuthController.php file... PhoneAuthController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class PhoneAuthController extends Controller {     public function index(){       return view('welcome');     } } Step 6: Add Route Open and create a new route by using the PhoneAuthController, add the following code in routes/web.php... web.php <?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\PhoneAuthController; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- */ Route::get('phone-auth', [PhoneAuthController::class, 'index']); Step 7: Set Up Blade View We are using the default welcome blade view file to create the auth form’s locus, add bootstrap 5, firebase, and jQuery scripts in this template, add some custom functions that handle the phone auth in firebase. Open and replace with the following code in resources/views/welcome.blade.php... welcome.blade.php <!DOCTYPE html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <head>     <meta charset="utf-8">     <meta name="viewport" content="width=device-width, initial-scale=1">     <title>Laravel 8 Phone Number OTP Authentication - meaningarticles.com</title>     <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet"> </head> <body>     <div class="container mt-5" style="max-width: 550px">         <div class="alert alert-danger" id="error" style="display: none;"></div>         <h3>Add Phone Number</h3>         <div class="alert alert-success" id="successAuth" style="display: none;"></div>         <form>             <label>Phone Number:</label>             <input type="text" id="number" class="form-control" placeholder="+91 ********">             <div id="recaptcha-container"></div>             <button type="button" class="btn btn-primary mt-3" onclick="sendOTP();">Send OTP</button>         </form>         <div class="mb-5 mt-5">             <h3>Add verification code</h3>             <div class="alert alert-success" id="successOtpAuth" style="display: none;"></div>             <form>                 <input type="text" id="verification" class="form-control" placeholder="Verification code">                 <button type="button" class="btn btn-danger mt-3" onclick="verify()">Verify code</button>             </form>         </div>     </div>     <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>     <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->     <script src="https://www.gstatic.com/firebasejs/6.0.2/firebase.js"></script>     <script>         var 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"         };         firebase.initializeApp(firebaseConfig);     </script>     <script type="text/javascript">         window.onload = function () {             render();         };         function render() {             window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');             recaptchaVerifier.render();         }         function sendOTP() {             var number = $("#number").val();             firebase.auth().signInWithPhoneNumber(number, window.recaptchaVerifier).then(function (confirmationResult) {                 window.confirmationResult = confirmationResult;                 coderesult = confirmationResult;                 console.log(coderesult);                 $("#successAuth").text("Message sent");                 $("#successAuth").show();             }).catch(function (error) {                 $("#error").text(error.message);                 $("#error").show();             });         }         function verify() {             var code = $("#verification").val();             coderesult.confirm(code).then(function (result) {                 var user = result.user;                 console.log(user);                 $("#successOtpAuth").text("Auth is successful");                 $("#successOtpAuth").show();             }).catch(function (error) {                 $("#error").text(error.message);                 $("#error").show();             });         }     </script> </body> </html> Step 8: Start Development Server You may quickly test the application; just type the suggested command on the terminal, execute it start the development server. php artisan serve Use the following url to send the otp to authenticate using the phone number via firebase. http://127.0.0.1:8000/phone-auth
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.
Make Authentication System with VueJs and Google Firebase
In this tutorial, we will learn how to integrate Firebase Authentication in Vue.js 2+ application. We will additionally learn to register a utilizer, authenticate a utilizer and send password reset mail and logout from firebase app utilizing Vue.js application. We will utilize Firebase database to integrate authentication in Vue project from scratch. Firebase is a robust genuine-time database which offers Backend-as-a-accommodation. Firebase offers tons of utilizer authentication features such as Signin/Signup with Email and Password, Facebook, Google, Twitter, GitHub, Phone Number etc. In this tutorial, we’ll be engendering a rudimentary Vue app from scratch, integrating Firebase to vue app. We’ll engender the utilizer registration, utilizer authenticate with email/password, forgot password, logout utilizing sundry vue.js components and Firebase utilizer authentication API. If you are an abecedarian in Vue front-end development, then you must check out the following topics that we have covered anteriorly. Install and Setup Vue Project Install latest version of Vue CLI to getting started with Vue. # npm npm install -g @vue/cli # yarn yarn global add @vue/cli Create a new Vue project and get inside of it using below command. vue create vue-firebase-auth && cd vue-firebase-auth Start VUE app by using following command: npm run serve Add Bootstrap & Global CSS in Vue Install Bootstrap 4 module in Vue project. npm install bootstrap # or yarn add bootstrap Open main.js file and import the Bootstrap path inside of it. 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') Next, include global styling in a Vue app. Create src/assets/css folder then create the main.css file. Add the global CSS path inside the main.js file right after the Bootstrap path. import Vue from 'vue' import App from './App.vue' import router from './router' import 'bootstrap/dist/css/bootstrap.min.css' import '@/assets/css/main.css' Vue.config.productionTip = false new Vue({ router, render: h => h(App) }).$mount('#app') Add the following styling code in assets/css/main.css file. * { box-sizing: border-box; } body { background: #2554FF !important; min-height: 100vh; display: flex; font-weight: 400; } body, html, .App, .vue-tempalte, .vertical-center { width: 100%; height: 100%; } .navbar-light { background-color: #ffffff; box-shadow: 0px 14px 80px rgba(34, 35, 58, 0.2); } .vertical-center { display: flex; text-align: left; justify-content: center; flex-direction: column; } .inner-block { width: 450px; margin: auto; background: #ffffff; box-shadow: 0px 14px 80px rgba(34, 35, 58, 0.2); padding: 40px 55px 45px 55px; border-radius: 15px; transition: all .3s; } .vertical-center .form-control:focus { border-color: #2554FF; box-shadow: none; } .vertical-center h3 { text-align: center; margin: 0; line-height: 1; padding-bottom: 20px; } label { font-weight: 500; } .forgot-password, .forgot-password a { text-align: right; font-size: 13px; padding-top: 10px; color: #7a7a7a; margin: 0; } .forgot-password a { color: #2554FF; } .social-icons { text-align: center; font-family: "Open Sans"; font-weight: 300; font-size: 1.5em; color: #222222; } .social-icons ul { list-style: none; margin: 0; padding: 0; } .social-icons ul li { display: inline-block; zoom: 1; width: 65px; vertical-align: middle; border: 1px solid #e3e8f9; font-size: 15px; height: 40px; line-height: 40px; margin-right: 5px; background: #f4f6ff; } .social-icons ul li a { display: block; font-size: 1.4em; margin: 0 5px; text-decoration: none; } .social-icons ul li a i { -webkit-transition: all 0.2s ease-in; -moz-transition: all 0.2s ease-in; -o-transition: all 0.2s ease-in; -ms-transition: all 0.2s ease-in; transition: all 0.2s ease-in; } .social-icons ul li a:focus i, .social-icons ul li a:active i { transition: none; color: #222222; } Create Components for Firebase Authentication To manage the Firebase authentication in Vue app, we need to create the following components. Go to src/components folder and create the following files. Login.vue Signup.vue Home.vue ForgotPassword.vue An example of Vue component. <template> <div> <!-- Content goes here --> </div> </template> <script> export default { data() { return {...} } } </script> Create Routers and Enable Navigation Go to src/router/index.js file and replace with the existing code. import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter) const routes = [ { path: '/', name: 'signup', component: () => import('../components/Signup.vue') }, { path: '/login', name: 'login', component: () => import('../components/Login.vue') }, { path: '/forgot-password', name: 'forgot-password', component: () => import('../components/ForgotPassword.vue') }, { path: '/home', name: 'home', component: () => import('../components/Home.vue') } ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router We are all set with the /signup, /login, /forgort-password and /home routes next we will create a navigation header using Bootstrap nav-bar component. Open src/App.vue file and the following code. <template> <div class="vue-tempalte"> <!-- Navigation --> <nav class="navbar shadow bg-white rounded justify-content-between flex-nowrap flex-row fixed-top"> <div class="container"> <a class="navbar-brand float-left" href="https://laravelcode.com" target="_blank"> LaravelCode </a> <ul class="nav navbar-nav flex-row float-right"> <li class="nav-item"> <router-link class="nav-link pr-3" to="/login">Sign in</router-link> </li> <li class="nav-item"> <router-link class="btn btn-outline-primary" to="/">Sign up</router-link> </li> </ul> </div> </nav> <!-- Main --> <div class="App"> <div class="vertical-center"> <div class="inner-block"> <router-view /> </div> </div> </div> </div> </template> Set up Firebase Project We need to create a Firebase project to get started with Vue and Firebase Authentication. Go to console.firebase.google.com to create a Firebase project. Click “Create a project”. Click on “Continue” to generate the project. Click on the web icon. Enter the project name and click on “Next” Take Firebase configuration details we will need it later to connect Vue with Firebase. Click on “Authentication”. As we can see, Firebase is offering lots of authentication providers that can easily allow you to authenticate using social channels, email/password and phone number. We only need to enable the Email/Password auth provider. Add Firebase in Vue To add the Firebase in the Vue app, we need to install the Firebase plugin using the following command. npm install firebase Next, go to main.js file here we have to import the Firebase module and add the Firebase configuration details. import Vue from 'vue' import App from './App.vue' import router from './router' import * as firebase from 'firebase'; import 'bootstrap/dist/css/bootstrap.min.css' import '@/assets/css/main.css' Vue.config.productionTip = false 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" } firebase.initializeApp(firebaseConfig); new Vue({ router, render: h => h(App) }).$mount('#app') User Registration with Email/Password We are going to register a user with the name, email and password. Open the src/components/Signup.vue file and place the following code. <template> <div class="vue-tempalte"> <form @submit.prevent="userRegistration"> <h3>Sign Up</h3> <div class="form-group"> <label>Name</label> <input type="text" class="form-control form-control-lg" v-model="user.name" /> </div> <div class="form-group"> <label>Email</label> <input type="email" class="form-control form-control-lg" v-model="user.email" /> </div> <div class="form-group"> <label>Password</label> <input type="password" class="form-control form-control-lg" v-model="user.password" /> </div> <button type="submit" class="btn btn-dark btn-lg btn-block"> Sign Up </button> <p class="forgot-password text-right"> Already registered <router-link :to="{name: 'login'}">sign in?</router-link> </p> </form> </div> </template> <script> import firebase from "firebase"; export default { data() { return { user: { name: '', email: '', password: '' } }; }, methods: { userRegistration() { firebase .auth() .createUserWithEmailAndPassword(this.user.email, this.user.password) .then((res) => { res.user .updateProfile({ displayName: this.user.name }) .then(() => { this.$router.push('/login') }); }) .catch((error) => { alert(error.message); }); } } }; </script> To create a new user account via Vue frontend with a name, email and password fields, we took the following approach. We created a new sign-up form in Vue with Bootstrap. To register a new user, we called createUserWithEmailAndPassword() method and passed user email and password. Vue Firebase Login Example Let’s implement user login in Vue app with Firebase API, we need correct email and password to access in the app. So, Open the src/components/Login.vue file and include the following code. <template> <div class="vue-tempalte"> <form @submit.prevent="userLogin"> <h3>Sign In</h3> <div class="form-group"> <label>Email address</label> <input type="email" class="form-control form-control-lg" v-model="user.email" /> </div> <div class="form-group"> <label>Password</label> <input type="password" class="form-control form-control-lg" v-model="user.password" /> </div> <button type="submit" class="btn btn-dark btn-lg btn-block">Sign In</button> <p class="forgot-password text-right mt-2 mb-4"> <router-link to="/forgot-password">Forgot password ?</router-link> </p> </form> </div> </template> <script> import firebase from "firebase"; export default { data() { return { user: { email: '', password: '' } }; }, methods: { userLogin() { firebase .auth() .signInWithEmailAndPassword(this.user.email, this.user.password) .then(() => { this.$router.push('/home') }) .catch((error) => { alert(error.message); }); } } }; </script> We are using signInWithEmailAndPassword(email, password) method and passing the registered email address and correct password to make the user login to our vue app. Send Password Reset Email Open the components/ForgotPassword.vue component and add the following code inside of it. <template> <div class="vue-tempalte"> <form @submit.prevent="forgetPassword"> <h3>Forgot Password</h3> <div class="form-group"> <label>Email</label> <input type="email" class="form-control form-control-lg" v-model="user.email" /> </div> <button type="submit" class="btn btn-dark btn-lg btn-block">Reset password</button> </form> </div> </template> <script> import firebase from "firebase"; export default { data() { return { user: { email: '' } }; }, methods: { forgetPassword() { firebase .auth() .sendPasswordResetEmail(this.user.email) .then(() => { alert('Check your registered email to reset the password!') this.user = { email: '' } }).catch((error) => { alert(error) }) } } }; </script> The sendPasswordResetEmail(email) method takes email id, and when it is appropriately called, it sends the password reset instruction on the registered email id. User Logout and Display Logged in User Data We are going to cover up how to logout from the Firebase and Vue app and display the logged in user’s data. Open the src/components/Home.vue file and place the following code. <template> <div class="vue-tempalte"> <h3>Welcome</h3> <p>{{user.displayName}}</p> <p>{{user.email}}</p> <button type="submit" class="btn btn-dark btn-lg btn-block" @click="logOut()"> Log out </button> </div> </template> <script> import firebase from "firebase"; export default { data() { return { user: null }; }, created() { firebase.auth().onAuthStateChanged((user) => { if (user) { this.user = user; } else { this.user = null; } }); }, methods: { logOut() { firebase.auth().signOut().then(() => { firebase.auth().onAuthStateChanged(() => { this.$router.push('/login') }) }) } } }; </script> In the given above source code, we are getting the logged-in user’s data when the auth state is changing. The auth.signOut() method logs out the user from the firebase app.
Laravel 5.6 - Prevent Block Multiple Login Of Same Credentials
Today we are share with you one common but verry important tutorial how to prevent block multiple login of same credentials in laravel application using laravel session token key and google firebase. yes you can done this type functionality using laravel seeeion key and google firebase. in this tutorials we are also use google firebase because when user login in your laravel application from another PC or device then another login user automatic logout without page refresh. it is also possible only use of laravel session key and token but one problem with laravel session key user must be page refresh then after logout not without page refresh. so, here we are also use google firebase and done prevent block multi login in laravel application. [ADDCODE] Recently we are work one laravel application and during done this project we are required prevent block multi login of same credentials with without page refresh. then we can done this using firebase and laravel token key. First we are searching on google but i was not find any perfect logic for this so, i apply my own logic and built this type functionality because i also know google firebase very well. Simply follow this step and you can built this type functionality in your laravel application. if you don't know more about google firebase then this link may be help you https://laravelcode.com/post/how-to-create-google-firebase-project You can also check our video link here YouTube Video Change in Users Table Migration: Now we are change in our users table migration and add one extra filed in users migration. if you already users table in your database then you can add one extra field in users table use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->string('password'); $table->string('session_id'); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); } } After done this then run your migration using following command. php artisan migrate Create Laravel Auth: first we are create laravel bydefault auth using following command. if you already make auth then you can skip this step. php artisan make:auth after run this command then look in you laravel application folder LoginController.php and some another files created automatic. but we are here use only LoginController.php file. because all login or logout logic you can write here and also overwrite all logincontroller method and function in this file. Change in LoginController.php File: Now, next step is change some in your app/Http/Controllers/Auth/LoginController.php file and simple copy and past following code in your LoginController namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Illuminate\Foundation\Auth\AuthenticatesUsers; use Illuminate\Http\Request; use App\Http\Requests; use App\User; use DB; class LoginController extends Controller { /* |-------------------------------------------------------------------------- | Login Controller |-------------------------------------------------------------------------- | | This controller handles authenticating users for the application and | redirecting them to your home screen. The controller uses a trait | to conveniently provide its functionality to your applications. | */ use AuthenticatesUsers; /** * Where to redirect users after login. * * @var string */ protected $redirectTo = '/home'; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('guest')->except('logout'); } public function login(Request $request) { $this->validate($request, [ 'email' => 'required', 'password' => 'required', ]); $user = \DB::table('users')->where('email', $request->input('email'))->first(); if (auth()->guard('web')->attempt(['email' => $request->input('email'), 'password' => $request->input('password')])) { $new_sessid = \Session::getId(); //get new session_id after user sign in if($user->session_id != '') { $last_session = \Session::getHandler()->read($user->session_id); if ($last_session) { if (\Session::getHandler()->destroy($user->session_id)) { } } } \DB::table('users')->where('id', $user->id)->update(['session_id' => $new_sessid]); $user = auth()->guard('web')->user(); return redirect($this->redirectTo); } \Session::put('login_error', 'Your email and password wrong!!'); return back(); } public function logout(Request $request) { \Session::flush(); \Session::put('success','you are logout Successfully'); return redirect()->to('/login'); } } Change in app.blade.php File: Now, we are add our google firebase code in resources/views/layouts/app.blade.php file. this code help to you when another user login with same email and password then previous account logout automatic without page refresh. Simply add following javascript google firebase code into the bottom of your app.blade.php file <script src="https://www.gstatic.com/firebasejs/4.9.1/firebase.js"></script> <script type="text/javascript"> var session_id = "{!! (Session::getId())?Session::getId():'' !!}"; var user_id = "{!! (Auth::user())?Auth::user()->id:'' !!}"; // Initialize Firebase var config = { apiKey: "firebase.api_key", authDomain: "firebase.auth_domain", databaseURL: "firebase.database_url", storageBucket: "firebase.storage_bucket", }; firebase.initializeApp(config); var database = firebase.database(); if({!! Auth::user() !!}) { firebase.database().ref('/users/' + user_id + '/session_id').set(session_id); } firebase.database().ref('/users/' + user_id).on('value', function(snapshot2) { var v = snapshot2.val(); if(v.session_id != session_id) { toastr.warning('Your account login from another device!!', 'Warning Alert', {timeOut: 3000}); setTimeout(function() { window.location = '/login'; }, 4000); } }); </script> 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/login 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
Firebase Phone Authentication With Invisible reCaptcha in Laravel5.6
Today, we are share with you how to implement firebase phone authentication with invisible reCaptcha with custome UI in your laravel application. Many developer need to built firebase phone auth with invisible reCaptcha with cusome UI not use Google Firebase UI. so in this tutorials we are show you how to integrate and make this functionality in your application. this is very easy and use in any php application if you don't know how to create firebase project or set up then please you can visit this link and easily create it How to create firebase project. So, please simply follow this step Create Route: First, we need to create following route in routes/web.php file. Route::get('firebase-phone-authentication', 'HomeController@invisiblecaptcha')->name('invisiblecaptcha'); Add method in Homecontroller: Now, we are open HomeController.php file and add following method in home controller. namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; class HomeController extends Controller { public function __construct() { // $this->middleware('auth'); } public function invisiblecaptcha() { return view('invisiblecaptcha'); } Create invisiblecaptcha.blade.php file: Now, we are cleare one invisiblecaptcha.blade.php file in our resources/views folder and simple add following code in this file. Note : Here we are also add some css/js cdn so please first you need also create style or jquery section in your layout.blade.php file. @extends('layouts.app') @section('style') <link rel="stylesheet" href="https://code.getmdl.io/1.1.3/material.orange-indigo.min.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <script defer src="https://code.getmdl.io/1.1.3/material.min.js"></script> @endsection @section('content') <div class="container"> <div class="row"> <div class="col-md-12"> <div class="card card-default"> <div class="card-header"> <div class="row"> <div class="col-md-12"> <strong>Laravelcode - Google Firebase Phone No. Auththentication With No reCaptcha Using Custom UI</strong> </div> </div> </div> <div class="card-body"> <form id="sign-in-form" action="#"> <!-- Input to enter the phone number --> <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label"> <input class="mdl-textfield__input" type="text" pattern="\+[0-9\s\-\(\)]+" id="phone-number"> <label class="mdl-textfield__label" for="phone-number">Enter your phone number...</label> <span class="mdl-textfield__error">Input is not an international phone number!</span> </div> <code>Ex. +919898989898</code> <!-- Sign-in button --> <button disabled class="mdl-button mdl-js-button mdl-button--raised" id="sign-in-button">Sign-in</button> </form> <!-- Button that handles sign-out --> <button class="mdl-button mdl-js-button mdl-button--raised" id="sign-out-button">Sign-out</button> <form id="verification-code-form" action="#"> <!-- Input to enter the verification code --> <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label"> <input class="mdl-textfield__input" type="text" id="verification-code"> <label class="mdl-textfield__label" for="verification-code">Enter the verification code...</label> </div> <!-- Button that triggers code verification --> <input type="submit" class="mdl-button mdl-js-button mdl-button--raised" id="verify-code-button" value="Verify Code"/> <!-- Button to cancel code verification --> <button class="mdl-button mdl-js-button mdl-button--raised" id="cancel-verify-code-button">Cancel</button> </form> </div> </div> </div> </div> <br /> <br /> <div class="row"> <div class="col-md-12"> <div class="card card-default"> <div class="card-header"> <div class="row"> <div class="col-md-12"> <strong>Laravelcode - User sign-in status</strong> </div> </div> </div> <div class="card-body"> <div class="user-details-container"> Firebase sign-in status: <span id="sign-in-status">Unknown</span> <div>Firebase auth <code>currentUser</code> object value:</div> <pre><code id="account-details">null</code></pre> </div> </div> </div> </div> </div> </div> @endsection @section('jquery') <!-- Here your js code --> @endsection Now, put following javascript code in your jquery section <script src="https://www.gstatic.com/firebasejs/4.9.1/firebase.js"></script> <script type="text/javascript"> // Initialize Firebase var config = { apiKey: "api_key", authDomain: "auth_domain", databaseURL: "database_url", storageBucket: "storage_bucket", messagingSenderId: "messagingSenderId", }; firebase.initializeApp(config); var database = firebase.database(); /** * Set up UI event listeners and registering Firebase auth listeners. */ window.onload = function() { // Listening for auth state changes. firebase.auth().onAuthStateChanged(function(user) { if (user) { // User is signed in. var uid = user.uid; var email = user.email; var photoURL = user.photoURL; var phoneNumber = user.phoneNumber; var isAnonymous = user.isAnonymous; var displayName = user.displayName; var providerData = user.providerData; var emailVerified = user.emailVerified; } updateSignInButtonUI(); updateSignInFormUI(); updateSignOutButtonUI(); updateSignedInUserStatusUI(); updateVerificationCodeFormUI(); }); // Event bindings. document.getElementById('sign-out-button').addEventListener('click', onSignOutClick); document.getElementById('phone-number').addEventListener('keyup', updateSignInButtonUI); document.getElementById('phone-number').addEventListener('change', updateSignInButtonUI); document.getElementById('verification-code').addEventListener('keyup', updateVerifyCodeButtonUI); document.getElementById('verification-code').addEventListener('change', updateVerifyCodeButtonUI); document.getElementById('verification-code-form').addEventListener('submit', onVerifyCodeSubmit); document.getElementById('cancel-verify-code-button').addEventListener('click', cancelVerification); // [START appVerifier] window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('sign-in-button', { 'size': 'invisible', 'callback': function(response) { // reCAPTCHA solved, allow signInWithPhoneNumber. onSignInSubmit(); } }); // [END appVerifier] recaptchaVerifier.render().then(function(widgetId) { window.recaptchaWidgetId = widgetId; updateSignInButtonUI(); }); }; /** * Function called when clicking the Login/Logout button. */ function onSignInSubmit() { if (isPhoneNumberValid()) { window.signingIn = true; updateSignInButtonUI(); var phoneNumber = getPhoneNumberFromUserInput(); var appVerifier = window.recaptchaVerifier; firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier) .then(function (confirmationResult) { // SMS sent. Prompt user to type the code from the message, then sign the // user in with confirmationResult.confirm(code). window.confirmationResult = confirmationResult; window.signingIn = false; updateSignInButtonUI(); updateVerificationCodeFormUI(); updateVerifyCodeButtonUI(); updateSignInFormUI(); }).catch(function (error) { // Error; SMS not sent console.error('Error during signInWithPhoneNumber', error); window.alert('Error during signInWithPhoneNumber:\n\n' + error.code + '\n\n' + error.message); window.signingIn = false; updateSignInFormUI(); updateSignInButtonUI(); }); } } /** * Function called when clicking the "Verify Code" button. */ function onVerifyCodeSubmit(e) { e.preventDefault(); if (!!getCodeFromUserInput()) { window.verifyingCode = true; updateVerifyCodeButtonUI(); var code = getCodeFromUserInput(); confirmationResult.confirm(code).then(function (result) { // User signed in successfully. var user = result.user; window.verifyingCode = false; window.confirmationResult = null; updateVerificationCodeFormUI(); }).catch(function (error) { // User couldn't sign in (bad verification code?) console.error('Error while checking the verification code', error); window.alert('Error while checking the verification code:\n\n' + error.code + '\n\n' + error.message); window.verifyingCode = false; updateSignInButtonUI(); updateVerifyCodeButtonUI(); }); } } /** * Cancels the verification code input. */ function cancelVerification(e) { e.preventDefault(); window.confirmationResult = null; updateVerificationCodeFormUI(); updateSignInFormUI(); } /** * Signs out the user when the sign-out button is clicked. */ function onSignOutClick() { firebase.auth().signOut(); } /** * Reads the verification code from the user input. */ function getCodeFromUserInput() { return document.getElementById('verification-code').value; } /** * Reads the phone number from the user input. */ function getPhoneNumberFromUserInput() { return document.getElementById('phone-number').value; } /** * Returns true if the phone number is valid. */ function isPhoneNumberValid() { var pattern = /^\+[0-9\s\-\(\)]+$/; var phoneNumber = getPhoneNumberFromUserInput(); return phoneNumber.search(pattern) !== -1; } /** * Re-initializes the ReCaptacha widget. */ function resetReCaptcha() { if (typeof grecaptcha !== 'undefined' && typeof window.recaptchaWidgetId !== 'undefined') { grecaptcha.reset(window.recaptchaWidgetId); } } /** * Updates the Sign-in button state depending on ReCAptcha and form values state. */ function updateSignInButtonUI() { document.getElementById('sign-in-button').disabled = !isPhoneNumberValid() || !!window.signingIn; } /** * Updates the Verify-code button state depending on form values state. */ function updateVerifyCodeButtonUI() { document.getElementById('verify-code-button').disabled = !!window.verifyingCode || !getCodeFromUserInput(); } /** * Updates the state of the Sign-in form. */ function updateSignInFormUI() { if (firebase.auth().currentUser || window.confirmationResult) { document.getElementById('sign-in-form').style.display = 'none'; } else { resetReCaptcha(); document.getElementById('sign-in-form').style.display = 'block'; } } /** * Updates the state of the Verify code form. */ function updateVerificationCodeFormUI() { if (!firebase.auth().currentUser && window.confirmationResult) { document.getElementById('verification-code-form').style.display = 'block'; } else { document.getElementById('verification-code-form').style.display = 'none'; } } /** * Updates the state of the Sign out button. */ function updateSignOutButtonUI() { if (firebase.auth().currentUser) { document.getElementById('sign-out-button').style.display = 'block'; } else { document.getElementById('sign-out-button').style.display = 'none'; } } /** * Updates the Signed in user status panel. */ function updateSignedInUserStatusUI() { var user = firebase.auth().currentUser; if (user) { document.getElementById('sign-in-status').textContent = 'Signed in'; document.getElementById('account-details').textContent = JSON.stringify(user, null, ' '); } else { document.getElementById('sign-in-status').textContent = 'Signed out'; document.getElementById('account-details').textContent = 'null'; } } </script> 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/firebase-phone-authentication 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.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.6 - Google Firebase Notification In Android
Today, We are going to share with you guys how to send push notification in android with google fire-base using laravel. Sometime ago we have worked on one android application application managed in laravel. so, we need to fire a push notification on every android device when admin insert any new product from laravel application. so, we are done this push notification task with google firebase and google firebase is awesome for send push notification and other more functionality. today we are share with you how to work with google firebase for send push notification in android devise. Simply foolow this step and done your push notification in android with google firebase using laravel backend. [ADDCODE] What we done in this article: We are create one simple post table and when admin insert any post then automatic fire notication on register user's mobile by firebase token. so first you must be also get google firebase token from users android mobile by your android app. Create New Project In Firebase: First we need to create one fresh project in google firebase. you can create your project click by this link Google Firebase Console How to crete your first project in google firebase please visite 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 This all things you got from your google firebase project easily Create post table migration: Now, we are create one post table migration run by following command php artisan make:migration create_post_table After run this command in your database/migration folder. so, open it and copy past following code in this file. use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * @return void */ public function up() { Schema::create('post', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->text('description'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('post'); } } Then run your post table migration by run following command. php artisan migrate Create Route: Now create folloeing resource route in routes/web.php file. Route::resource('post', 'PostController'); Create PostController: Now create PostController.php in app/Http/Controllers/ folder and write following code in store method so when your post create then Notification automaticly fire of users mobile by google firebase namespace App\Http\Controllers; use App\Http\Requests; use Illuminate\Http\Request; use App\Post; class PostController extends HomeController { public function __construct() { parent::__construct(); $this->Post = new Post; } public function store(Request $request) { $this->validate($request, [ 'title' => 'required|max:255', 'description' => 'required', ]); $input = array_except($request->all(),array('_token')); $this->Post->AddData($input); $notification = \DB::table('api_users')->get(); foreach ($notification as $key => $value) { $this->notification($value->token, $request->get('title')); } \Session::put('success','Post store and send notification successfully!!'); return redirect()->route('post.index'); } public function notification($token, $title) { $fcmUrl = 'https://fcm.googleapis.com/fcm/send'; $token=$token; $notification = [ 'title' => $title, 'sound' => true, ]; $extraNotificationData = ["message" => $notification,"moredata" =>'dd']; $fcmNotification = [ //'registration_ids' => $tokenList, //multple token array 'to' => $token, //single token 'notification' => $notification, 'data' => $extraNotificationData ]; $headers = [ 'Authorization: key=Legacy server key', 'Content-Type: application/json' ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$fcmUrl); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fcmNotification)); $result = curl_exec($ch); curl_close($ch); return true; } } In this store method you cann look we are get token from api_users table so we should be first get google firebase token from your android side app and that token store in your database. so, you can fire easily notification for all user. If you can test notification manualy then you can use following code for testing for one mobile devise. public function test() { $fcmUrl = 'https://fcm.googleapis.com/fcm/send'; $token='diWhHpEdy1k:APA91bHfaE_zy4FUJ_GGDmO3XuJNz5qshyMeyjbIvvdLKI-DkR5rzhS00k9Hwc49yKzJLUraUPbu9-H-XOv8hbT-q-omtzXa8-uAv8Ewej52zO1gH0maKoGP4FLCu9FwVlLSpwBDC_3T'; $notification = [ 'body' => 'this is test', 'sound' => true, ]; $extraNotificationData = ["message" => $notification,"moredata" =>'dd']; $fcmNotification = [ //'registration_ids' => $tokenList, //multple token array 'to' => $token, //single token 'notification' => $notification, 'data' => $extraNotificationData ]; $headers = [ 'Authorization: key=Legacy server key', 'Content-Type: application/json' ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$fcmUrl); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fcmNotification)); $result = curl_exec($ch); curl_close($ch); dd($result); } Legacy server key you can seen in your firebase setting then go in secound cloud messaging tab 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