Xây dụng chức năng Register+ Login bằng Laravel 5.4 + VueJS

Xin chào mọi người, nay mình sẽ chia sẽ với mọi người về sự kết hợp giữa Laravel 5.4 + Vuejs nhé xây dựng chức năng đăng ký và đăng nhập, hiển thị danh sách thành viên trong cơ sở dữ liệu ra nhé, ở bài trước mình đã chia sẽ với các bạn cách kết hợp Laravel 5.4 + Vuejs cũng hướng dẫn cách cài đặt thư viện Vuejs tích hợp vào Laravel bạn có thể xem lại bài TẠO ỨNG DỤNG LARAVEL 5.4 KẾT HỢP VỚI VUEJS

Bài này mình sẽ bỏ qua các bước cài đặt thư viện cũng như tạo database,table, mình chỉ tích hợp thêm tính năng thôi, ở bài này mình đã có một bảng users trong trong database như sau

 Chúng ta đã có table giờ chúng ta tạo file DangkyController thông qua câu lệnh: php artisan make:controller --resource
 Ở đây mình có các hảm như sau: 
 - function index(): Dùng lấy danh sách user trong database và trả về kiểu json cho vuejs xử lý phần hiển thị danh sách lên template
 - function store(): Dùng thêm một thành viên mới vào cở dữ liệu khi chúng ta submit form đăng ký
 - function loginUser(): Dùng để kiểm tra tính đăng nhập của form khi chúng ta submit form đăng nhập

* Các bạn copy đoạn code DangkyController.php bên dưới vào file:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
class DangkyController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $lists = User::all();
       return response()->json($lists);

    }

    /**
     * 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)
    {
    	// dùng thêm một thành viên mới
        $user = new User;
        $user->name=$request->name;
        $user->email=$request->email;
        $user->password = hash('md5', $request->pass);
        $user->save();
    }

    // login
    public function loginUser(Request $request){
       $email = $request->email; //lấy email của phương thức post vuejs gửi qua
       $pass = $request->pass;  //lấy pass của phương thức post vuejs gửi qua

       //kiểm tra email và pass trong CSDL
       $data = User::where('email','=',$email)->where('password','=',hash('md5',$pass))->get();
                
        if(count($data)>0){
            if($data[0]->email==$email && $data[0]->pass=hash("md5",$pass)){
                //return response()->json($data[0]->email);

                //nếu đúng trả về 1
                return response()->json(array("success"=>1));
            }
        }else{

        	//nếu sai trả về 0
            return response()->json(array("success"=>0));
        }
        
    }



    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

}
?>

Tiếp theo chúng ta phải thiết lặp Route để xử lý điều hướng, các bạn mở file web.php trong đường dẫn C:\xampp\htdocs\laravel_vuejs\routes này và chỉnh sửa lại như sau:
 

Route::get('/', function () {
    return view('home');
});
Route::resource('dangky', 'DangkyController');

Route::post('/dangky/loginUser','DangkyController@loginUser');//dùng post đăng nhập

Vậy là kết thúc phần bên laravel, giờ chúng ta tới phần xử lý backend ở Vuejs
Tiếp theo bạn tạo cho mình các file như sau tại đường dẫn C:\xampp\htdocs\laravel_vuejs\resources\assets\js\components\register
- CreateRegister.vue : File này dùng để hiện thị form đăng ký thành viên
- ListUser.vue : File này dùng để hiện thị danh sách thành viên
- LoginUser.vue : File này dùng để hiện thị form đăng nhập thành viên
các bạn có thể xem hình thư mục như sau:

Tiếp theo các bạn copy từng đoạn code của từng file vào đúng vị trí nhé

* Source ListUser.vue

<template>
	<div class="row">
		<div class="col-md-2"></div>
		<div class="col-md-8">
			<div class="row">
				<div class="col-md-12">
					<h1 class="btn btn-danger">List User</h1>
					<h1 class="btn btn-warning"><router-link :to="{name:'CreateRegister'}">Add User</router-link></h1>
					<h1 class="btn btn-info"><router-link :to="{name:'LoginUser'}">Login User</router-link></h1>
						<table class="table">
							<thead>
								<tr>
									<th>Name</th>
									<th>Email</th>
									<th>Password</th>
									<th>Created at</th>
								</tr>
							</thead>
							<tbody>
								<tr v-for="user in users">
									<td>{{user.name}}</td>
									<td>{{user.email}}</td>
									<td>{{user.password}}</td>
									<td>{{user.created_at}}</td>
								</tr>
							</tbody>
						</table>
		
					</form>
				</div>
			</div>
		</div>
		<div class="col-md-2"></div>
	</div>
</template>
<script>
	export default{
		data(){
			return {
				users:[]
			}
		},
		created:function(){
			this.listUser();
		},
		methods:{
			listUser(){
				this.axios.get("https://localhost:8000/dangky").then((response)=>{
					this.users=response.data;
				});
			}
		}
	}
</script>

* Source CreateRegister.vue

<template>
	<div class="row">
		<div class="col-md-4"></div>
		<div class="col-md-4">
			<div class="row">
				<div class="col-md-12">
					<h1 class="btn btn-danger">Register User</h1>
					<form action="" method="post" v-on:submit.prevent="onSubmit">

						<table class="table">
							<tbody>
								<tr>
									<td>Full Name</td>
									<td><input type="text" name="name" v-model="user.name" class="form-control" placeholder="Enter name"></td>
								</tr>
								<tr>
									<td>Email</td>
									<td><input type="email" name="email" v-model="user.email" class="form-control" placeholder="Enter email"></td>
								</tr>
								<tr>
									<td>Password</td>
									<td><input type="password" name="pass" v-model="user.pass" class="form-control" placeholder="Enter password"></td>
								</tr>
								<tr>
									<td colspan="2" align="center"><button class="btn btn-warning">Register</button>
									<label class="label label-success" v-if="check">Them thanh cong</label><br/>
									<router-link :to="{name:'ListUser'}" class="label label-primary" v-if="check">Back List User</router-link>
									</td>
								</tr>
							</tbody>
						</table>
		
					</form>
				</div>
			</div>
		</div>
		<div class="col-md-4"></div>
	</div>
</template>
<script>
	export default{
		data(){
			return{
				user:{},
				check:false
			}
		},
		methods:{
			onSubmit(){
				this.axios.post("https://localhost:8000/dangky",this.user).then((response)=>{
					this.check=true;
					
				});
			}
		}
	}
</script>

* Source LoginUser.vue

<template>
	<div class="row">
		<div class="col-md-4"></div>
		<div class="col-md-4">
			<div class="row">
				<div class="col-md-12">
					<h1 class="btn btn-danger">Login User</h1>
					<form action="" method="post" v-on:submit.prevent="onSubmit">
						<table class="table">
							<tbody>
								<tr>
									<td>Email</td>
									<td><input type="email" name="email" v-model="user.email" class="form-control" placeholder="Enter email"></td>
								</tr>
								<tr>
									<td>Password</td>
									<td><input type="password" name="pass" v-model="user.pass" class="form-control" placeholder="Enter password"></td>
								</tr>
								<tr>
									<td colspan="2" align="center"><button class="btn btn-warning">Login</button>
										<label class="label label-success" v-if="check_a">Login thanh cong</label><br/>
										<label class="label label-success" v-if="check_b">Login Khong thanh cong</label><br/>
									</td>
								</tr>
							</tbody>
						</table>
		
					</form>
				</div>
			</div>
		</div>
		<div class="col-md-4"></div>
	</div>
</template>
<script>
	export default{
		data(){
			return{
				user:{},
				check_a:false,
				check_b:false
			}
		},
		methods:{
			onSubmit(){
				this.axios.post("https://localhost:8000/dangky/loginUser",this.user).then((response)=>{
					var data = response.data.success;
					if(data>0){
						this.check_a=true;
						this.check_b=false;
					}
					else{
						this.check_a=false;
						this.check_b=true;
					}

				});
			}
		}
	}
</script>

- Sau khi các bạn copy vào đúng từng file thì chúng ta cần import các template bên trên vào file app.js
tại đường dẫn như này C:\xampp\htdocs\laravel_vuejs\resources\assets\js mở file app.js lên sửa thành như sau:

import Vue from 'Vue';

import VueRouter from 'vue-router';
Vue.use(VueRouter);

import VueAxios from 'vue-axios';//gọi thư viện axios
import axios from 'axios';
Vue.use(VueAxios,axios);


import App from './App.vue';
//incldue listsp
import ListUser from './components/register/ListUser.vue'; //import template danh sách hiển thị listuser
import CreateRegister from './components/register/CreateRegister.vue';
import LoginUser from './components/register/LoginUser.vue';

//thiết lặp routes
const routes = [
  {
      name: 'ListUser',
      path: '/',
      component: ListUser
  },
  {
  	name:'CreateRegister',
  	path:'/dangky/create',
  	component:CreateRegister
  },
  {
  	name:'LoginUser',
  	path:'/dangky/login',
  	component:LoginUser
  }
];

const router = new VueRouter({mode:'history', routes: routes});
new Vue(Vue.util.extend({router},App)).$mount('#app');

Chú ý ở đây mình làm ngắn lại các bước , các bạn xem phần TẠO ỨNG DỤNG KẾT HỢP LARAVEL VỚI VUEJS ở bài trước, để bài này làm cho hoàn chỉnh nhé! vì mình bỏ quả các file ban đầu cần có như: App.vue bạn có thể copy 2 file kia ở bài trước nhé!

Tiếp theo bạn chỉ cần nhìn kết quả của mình thôi! bạn gỏ các câu lệnh như sau để khởi động server

npm run dev
php artisan serve

Sao đó bạn gỏ lên trình duyệt https://localhost:8000 để thấy kết quả của bạn làm nảy giờ nhé! chúc các bạn thành công!

Bài Viết Liên Quan

Messsage

Ủng hộ tôi bằng cách click vào quảng cáo. Để tôi có kinh phí tiếp tục phát triển Website!(Support me by clicking on the ad. Let me have the money to continue developing the Website!)