Hướng dẫn sử dụng Laravel với các chức năng (Create, Read, Update and Delete)

1. Tạo dự án mới bằng cách: composer create-project laravel/laravel  WebsiteLavarel

2. Dùng Visual Code Open thư mục WebsiteLavarel

3. Mở file .env trong thư mục root của dự án WebsiteLavarel

4. Tìm đến đoạn và chỉnh DB_DATABASE

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=WebsiteLavarel_Data
DB_USERNAME=root
DB_PASSWORD=
5. Tạo cơ sở dữ liệu với bảng students trong migration với câu lệnh chạy cmd
php artisan make:migration create_students_table
C:\xampp\htdocs\WebsiteLavarel>php artisan make:migration create_students_table
sau đó mở filestudents migrations trong thư mục database\migrations\_create_students_table.php và chỉnh sửa lại
<?php
 
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
 
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('students', function (Blueprint $table) {
            $table->id();
            $table->string("name");
            $table->string("address");
            $table->string("mobile");
            $table->timestamps();
        });
    }
 
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('students');
    }
};

 

6. Để tạo Database Migration chạy câu lệnh
php artisan migrate
C:\xampp\htdocs\WebsiteLavarel>php artisan migrate
Sau đó kiểm tra database WebsiteLavarel_Data đã có bảng students hay chưa?
7. Tạo Creating Controller chạy câu lênh sau
php artisan make:controller StudentController –resource
C:\xampp\htdocs\WebsiteLavarel>php artisan make:controller StudentController –resource
Tìm đến app\Http\Controllers\StudentController.php chỉnh sửa lại như sau:
<?php
 
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use App\Models\Student; //add Student Model - Data is coming from the database via Model.
 
class StudentController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $students = Student::all();
        return view ('students.index')->with('students', $students);
    }
 
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('students.create');
    }
 
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $input = $request->all();
        Student::create($input);
        return redirect('student')->with('flash_message', 'Thêm sinh viên thành công');  
    }
 
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $student = Student::find($id);
        return view('students.show')->with('students', $student);
    }
 
    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $student = Student::find($id);
        return view('students.edit')->with('students', $student);
    }
 
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $student = Student::find($id);
        $input = $request->all();
        $student->update($input);
        return redirect('student')->with('flash_message', 'Cập nhật sinh viên thành công');  
    }
 
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Student::destroy($id);
        return redirect('student')->with('flash_message', 'Xóa sinh viên thành công');  
    }
}

8. Tạo Create Model bằng câu lệnh sau:

php artisan make:model Student

C:\xampp\htdocs\WebsiteLavarel>php artisan make:model Student

Tìm đến app\Models\Student.php và mở file ra để sửa lại thành

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
 
class Student extends Model
{
    use HasFactory;
    protected $table = 'students';
    protected $primaryKey = 'id';
    protected $fillable = ['name', 'address', 'mobile'];
}

9. Tạo View giao diện web Create Views trong Resources/views

Tạo Layout trước resources\views\students\layout.blade.php 

<!DOCTYPE html>
<html>
<head>
    <title>Ứng dụng sinh viên sử dụng Lavarel</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
   
<div class="container">
    @yield('content')
</div>
   
</body>
</html>

resources\views\students\index.blade.php

@extends('students.layout')
@section('content')
    <div class="container">
        <div class="row" style="margin:20px;">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h4>Hướng dẫn sử dụng Laravel với các chức năng (Create, Read, Update and Delete)</h4>
                    </div>
                    <div class="card-body">
                        <a href="{{ url('/student/create') }}" class="btn btn-success btn-sm" title="THÊM MỚI SINH VIÊN">
                            THÊM MỚI
                        </a>
                        <br/>
                        <br/>
                        <div class="table-responsive">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>Họ tên</th>
                                        <th>Địa chỉ</th>
                                        <th>Điện thoại</th>
                                        <th>Chức năng</th>
                                    </tr>
                                </thead>
                                <tbody>
                                @foreach($students as $item)
                                    <tr>
                                        <td>{{ $loop->iteration }}</td>
                                        <td>{{ $item->name }}</td>
                                        <td>{{ $item->address }}</td>
                                        <td>{{ $item->mobile }}</td>
  
                                        <td>
                                            <a href="{{ url('/student/' . $item->id) }}" title="View Student"><button class="btn btn-info btn-sm"><i class="fa fa-eye" aria-hidden="true"></i> View</button></a>
                                            <a href="{{ url('/student/' . $item->id . '/edit') }}" title="Edit Student"><button class="btn btn-primary btn-sm"><i class="fa fa-pencil-square-o" aria-hidden="true"></i> Edit</button></a>
  
                                            <form method="POST" action="{{ url('/student' . '/' . $item->id) }}" accept-charset="UTF-8" style="display:inline">
                                                {{ method_field('DELETE') }}
                                                {{ csrf_field() }}
                                                <button type="submit" class="btn btn-danger btn-sm" title="Delete Student" onclick="return confirm("Confirm delete?")"><i class="fa fa-trash-o" aria-hidden="true"></i> Delete</button>
                                            </form>
                                        </td>
                                    </tr>
                                @endforeach
                                </tbody>
                            </table>
                        </div>
  
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

resources\views\students\create.blade.php

@extends('students.layout')
@section('content')
  
<div class="card" style="margin:20px;">
  <div class="card-header">Thêm mới sinh viên</div>
  <div class="card-body">
       
      <form action="{{ url('student') }}" method="post">
        {!! csrf_field() !!}
        <label>Họ tên</label></br>
        <input type="text" name="name" id="name" class="form-control"></br>
        <label>Địa chỉ</label></br>
        <input type="text" name="address" id="address" class="form-control"></br>
        <label>Điện thoại</label></br>
        <input type="text" name="mobile" id="mobile" class="form-control"></br>
        <input type="submit" value="Lưu" class="btn btn-success"></br>
    </form>
    
  </div>
</div>
  
@stop

resources\views\students\edit.blade.php

@extends('students.layout')
@section('content')
  
<div class="card" style="margin:20px;">
  <div class="card-header">Chỉnh sửa sinh viên</div>
  <div class="card-body">
       
      <form action="{{ url('student/' .$students->id) }}" method="post">
        {!! csrf_field() !!}
        @method("PATCH")
        <input type="hidden" name="id" id="id" value="{{$students->id}}" id="id" />
        <label>Họ tên</label></br>
        <input type="text" name="name" id="name" value="{{$students->name}}" class="form-control"></br>
        <label>Địa chỉ</label></br>
        <input type="text" name="address" id="address" value="{{$students->address}}" class="form-control"></br>
        <label>Điện thoại</label></br>
        <input type="text" name="mobile" id="mobile" value="{{$students->mobile}}" class="form-control"></br>
        <input type="submit" value="Cập nhật" class="btn btn-success"></br>
    </form>
    
  </div>
</div>
  
@stop

resources\views\students\show.blade.php

@extends('students.layout')
@section('content')
  
<div class="card" style="margin:20px;">
  <div class="card-header">Thông tin sinh viên</div>
  <div class="card-body">
        <div class="card-body">
        <h5 class="card-title">Họ tên : {{ $students->name }}</h5>
        <p class="card-text">Địa chỉ : {{ $students->address }}</p>
        <p class="card-text">Điện thoại : {{ $students->mobile }}</p>
  </div>
    </hr>
  </div>
</div>

9. Tạo Routers để điều hướng web Creating Routes tại

routes\web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\StudentController; //Nhớ thêm cái này



Route::get('/', function () {
    return view('welcome');
});
 
Route::resource("/student", StudentController::class);

10. Sau đó chạy chương trình tại trình duyệt(Nhớ bật Xampp)

http://localhost:7979/WebsiteLavarel/public/student

11. Kết quả:

0/5 (0 Reviews)