By GokiSoft.com| 20:46 30/03/2022|
Học Laravel

[Video] Ôn tập - Chương trình quản lý sách + danh mục sách - Lập trình PHP, Laravel - C2108L

Ôn tập - Chương trình quản lý sách + danh mục sách - Lập trình PHP, Laravel



Phân tích:
category:
	- CategoryController
	- Route -> category.php
		- index: Hien thi danh sach danh muc
		- view: Hien thi form them danh muc
		- post: đẩy dữ liệu vào database
		- delete: Xoá dữ liêuk
		- edit: Hiển thị form sửa danh mục
		- confirm-edit: Update dữ liệu
	-> Cài method trong controller + view trong resources
product:
	Làm tương tự như trên


#Route

#product.php


<?php
use App\Http\Controllers\ProductController;

Route::group(['prefix' => 'product'], function() {
	Route::get('index', [ProductController::class, 'index'])->name('product-index');

	Route::get('view', [ProductController::class, 'view'])->name('product-view');

	Route::get('{href_param}.html', [ProductController::class, 'detail'])->name('product-detail');

	Route::get('edit', [ProductController::class, 'edit'])->name('product-edit');

	Route::post('post', [ProductController::class, 'post'])->name('product-post');

	Route::post('confirm-edit', [ProductController::class, 'confirmEdit'])->name('product-confirm-edit');

	Route::post('delete', [ProductController::class, 'delete'])->name('product-delete');
});


#category.php


<?php
use App\Http\Controllers\CategoryController;

Route::group(['prefix' => 'category'], function() {
	Route::get('index', [CategoryController::class, 'index'])->name('category-index');

	Route::get('view', [CategoryController::class, 'view'])->name('category-view');

	Route::get('edit', [CategoryController::class, 'edit'])->name('category-edit');

	Route::post('post', [CategoryController::class, 'post'])->name('category-post');

	Route::post('confirm-edit', [CategoryController::class, 'confirmEdit'])->name('category-confirm-edit');

	Route::post('delete', [CategoryController::class, 'delete'])->name('category-delete');
});

Controller


#ProductController.php


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class ProductController extends Controller
{
    public function index(Request $request)
    {
        $productList = DB::table('product')
            ->join('category', 'category.id', '=', 'product.category_id')
            ->select('product.*', 'category.name as category_name')
            ->get();

        return view('product.index', [
            'productList' => $productList,
            'index' => 0
        ]);
    }

    public function view(Request $request)
    {
        $categoryList = DB::table('category')
            ->get();

        return view('product.view', [
            'categoryList' => $categoryList
        ]);
    }

    public function edit(Request $request)
    {
        $product = DB::table('product')
            ->where('id', $request->id)
            ->get();
        if($product != null && count($product) > 0) {
            $product = $product[0];
        } else {
            return redirect()->route('product-index');
        }

        $categoryList = DB::table('category')
            ->get();

        return view('product.edit', [
            'product' => $product,
            'categoryList' => $categoryList
        ]);
    }

    public function detail(Request $request, $href_param)
    {
        $product = DB::table('product')
            ->where('href_param', $href_param)
            ->take(1)
            ->get();
        if($product != null && count($product) > 0) {
            return $product[0]->content;
        }
    }

    public function post(Request $request)
    {
        $title = $request->title;
        $category_id = $request->category_id;
        $price = $request->price;
        $content = $request->content;
        $created_at = $updated_at = date('Y-m-d H:i:s');
        $hrefParam = $this->exportParam($request->title);

        DB::table('product')
            ->insert([
                'title' => $title,
                'category_id' => $category_id,
                'price' => $price,
                'content' => $content,
                'created_at' => $created_at,
                'updated_at' => $updated_at,
                'href_param' => $hrefParam
            ]);

        return redirect()->route('product-index');
    }

    public function exportParam($str) {
        $str = trim($str);
        $str = $this->stripVN($str);
        $str = strtolower($str);
        $str = str_replace("_", " ", $str);
        $str = str_replace(".", " ", $str);
        $str = str_replace("[", " ", $str);
        $str = str_replace("]", " ", $str);
        $str = str_replace("-", " ", $str);
        $str = trim($str);
        $str = preg_replace('!\s+!', ' ', $str);
        $str = str_replace(" ", "-", $str);
        $str = preg_replace('/[^A-Za-z0-9\-]/', '', $str);

        return $str;
    }

    public function stripVN($str) {
        $str = strtolower($str);

        $str = preg_replace("/(à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ)/", 'a', $str);
        $str = preg_replace("/(è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ)/", 'e', $str);
        $str = preg_replace("/(ì|í|ị|ỉ|ĩ)/", 'i', $str);
        $str = preg_replace("/(ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ)/", 'o', $str);
        $str = preg_replace("/(ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ)/", 'u', $str);
        $str = preg_replace("/(ỳ|ý|ỵ|ỷ|ỹ)/", 'y', $str);
        $str = preg_replace("/(đ)/", 'd', $str);

        $str = preg_replace("/(À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ)/", 'A', $str);
        $str = preg_replace("/(È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ)/", 'E', $str);
        $str = preg_replace("/(Ì|Í|Ị|Ỉ|Ĩ)/", 'I', $str);
        $str = preg_replace("/(Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ)/", 'O', $str);
        $str = preg_replace("/(Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ)/", 'U', $str);
        $str = preg_replace("/(Ỳ|Ý|Ỵ|Ỷ|Ỹ)/", 'Y', $str);
        $str = preg_replace("/(Đ)/", 'D', $str);
        return $str;
    }

    public function confirmEdit(Request $request)
    {
        $title = $request->title;
        $category_id = $request->category_id;
        $price = $request->price;
        $content = $request->content;
        $updated_at = date('Y-m-d H:i:s');

        DB::table('product')
            ->where('id', $request->id)
            ->update([
                'title' => $title,
                'category_id' => $category_id,
                'price' => $price,
                'content' => $content,
                'updated_at' => $updated_at
            ]);

        return redirect()->route('product-index');
    }

    public function delete(Request $request)
    {
        $id = $request->id;

        DB::table('product')
            ->where('id', $id)
            ->delete();
    }
}


#CategoryController.php


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class CategoryController extends Controller
{
    public function index(Request $request)
    {
        $categoryList = DB::table('category')
            ->get();

        return view('category.index', [
            'categoryList' => $categoryList,
            'index' => 0
        ]);
    }

    public function view(Request $request)
    {
        return view('category.view');
    }

    public function edit(Request $request)
    {
        $category = DB::table('category')
            ->where('id', $request->id)
            ->take(1)
            ->get();
        if($category != null && count($category) > 0) {
            $category = $category[0];
        } else {
            return redirect()->route('category-index');
        }

        return view('category.edit', [
            'category' => $category
        ]);
    }

    public function post(Request $request)
    {
        $name = $request->name;

        DB::table('category')
            ->insert([
                'name' => $name
            ]);

        return redirect()->route('category-index');
    }

    public function confirmEdit(Request $request)
    {
        $name = $request->name;
        $id = $request->id;

        DB::table('category')
            ->where('id', $id)
            ->update([
                'name' => $name
            ]);

        return redirect()->route('category-index');
    }

    public function delete(Request $request)
    {
        $id = $request->id;

        DB::table('category')
            ->where('id', $id)
            ->delete();
    }
}

Migrationg


#2022_03_30_120510_create_product_table.php


<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateProductTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('product', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('category_id');
            $table->string('title', 250);
            $table->string('href_param', 250);
            $table->float('price');
            $table->text('content');
            $table->timestamps();
            $table->foreign('category_id')->references('id')->on('category');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('product');
    }
}


#2022_03_30_120422_create_category_table.php


<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateCategoryTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('category', function (Blueprint $table) {
            $table->id();
            $table->string('name', 50);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('category');
    }
}

View|product


#view.blade.php


@extends('layouts.master')

@section('content')
<div class="container">
	<form method="post" action="{{ route('product-post') }}">
		{{ csrf_field() }}
		<div class="form-group">
			<label>Title: </label>
			<input type="text" name="title" class="form-control">
		</div>
		<div class="form-group">
			<label>Category Name: </label>
			<select name="category_id" class="form-control">
				<option value="">-- Chon Danh Muc --</option>
				@foreach($categoryList as $item)
					<option value="{{ $item->id }}">{{ $item->name }}</option>
				@endforeach
			</select>
		</div>
		<div class="form-group">
			<label>Price: </label>
			<input type="num" name="price" class="form-control" step="0.1">
		</div>
		<div class="form-group">
			<label>Content: </label>
			<textarea class="form-control" rows="10" name="content"></textarea>
		</div>
		<div class="form-group">
			<button class="btn btn-success mt-2">Add Product</button>
		</div>
	</form>
</div>
@stop


#index.blade.php


@extends('layouts.master')

@section('content')
<div class="container">
	<a href="{{ route('product-view') }}"><button class="btn btn-success mb-2">Add Product</button></a>
	<table class="table table-bordered">
		<thead>
			<tr>
				<th>No</th>
				<th>Title</th>
				<th>Category Name</th>
				<th>Price</th>
				<th>Updated At</th>
				<th style="width: 60px"></th>
				<th style="width: 60px"></th>
			</tr>
		</thead>
		<tbody>
			@foreach($productList as $item)
				<tr>
					<td>{{ ++$index }}</td>
					<td>{{ $item->title }}</td>
					<td>{{ $item->category_name }}</td>
					<td>{{ number_format($item->price, 0) }}</td>
					<td>{{ $item->updated_at }}</td>
					<td>
						<a href="{{ route('product-edit') }}?id={{ $item->id }}"><button class="btn btn-warning">Edit</button></a>
					</td>
					<td>
						<button class="btn btn-danger" onclick="deleteItem({{ $item->id }})">Delete</button>
					</td>
				</tr>
			@endforeach
		</tbody>
	</table>
</div>
@stop

@section('js')
<script type="text/javascript">
	function deleteItem(id) {
		var option = confirm('Are you sure to delete this product?')
		if(!option) return

		$.post('{{ route('product-delete') }}', {
			'_token': '{{ csrf_token() }}',
			'id': id
		}, function(data) {
			location.reload()
		})
	}
</script>
@stop


#edit.blade.php


@extends('layouts.master')

@section('content')
<div class="container">
	<form method="post" action="{{ route('product-confirm-edit') }}">
		{{ csrf_field() }}
		<div class="form-group">
			<label>Title: </label>
			<input type="text" name="title" class="form-control" value="{{ $product->title }}">
			<input type="text" name="id" hidden value="{{ $product->id }}">
		</div>
		<div class="form-group">
			<label>Category Name: </label>
			<select name="category_id" class="form-control">
				<option value="">-- Chon Danh Muc --</option>
				@foreach($categoryList as $item)
					@if($item->id == $product->category_id)
						<option value="{{ $item->id }}" selected>{{ $item->name }}</option>
					@else
						<option value="{{ $item->id }}">{{ $item->name }}</option>
					@endif
				@endforeach
			</select>
		</div>
		<div class="form-group">
			<label>Price: </label>
			<input type="num" name="price" class="form-control" step="0.1" value="{{ $product->price }}">
		</div>
		<div class="form-group">
			<label>Content: </label>
			<textarea class="form-control" rows="10" name="content">{{ $product->content }}</textarea>
		</div>
		<div class="form-group">
			<button class="btn btn-success mt-2">Update Product</button>
		</div>
	</form>
</div>
@stop

view|category


#view.blade.php


@extends('layouts.master')

@section('content')
<div class="container">
	<form method="post" action="{{ route('category-post') }}">
		{{ csrf_field() }}
		<div class="form-group">
			<label>Category Name: </label>
			<input type="text" name="name" class="form-control">
		</div>
		<div class="form-group">
			<button class="btn btn-success mt-2">Add Category</button>
		</div>
	</form>
</div>
@stop


#index.blade.php


@extends('layouts.master')

@section('content')
<div class="container">
	<a href="{{ route('category-view') }}"><button class="btn btn-success mb-2">Add Category</button></a>
	<table class="table table-bordered">
		<thead>
			<tr>
				<th>No</th>
				<th>Category Name</th>
				<th style="width: 60px"></th>
				<th style="width: 60px"></th>
			</tr>
		</thead>
		<tbody>
			@foreach($categoryList as $item)
				<tr>
					<td>{{ ++$index }}</td>
					<td>{{ $item->name }}</td>
					<td>
						<a href="{{ route('category-edit') }}?id={{ $item->id }}"><button class="btn btn-warning">Edit</button></a>
					</td>
					<td>
						<button class="btn btn-danger" onclick="deleteItem({{ $item->id }})">Delete</button>
					</td>
				</tr>
			@endforeach
		</tbody>
	</table>
</div>
@stop

@section('js')
<script type="text/javascript">
	function deleteItem(id) {
		var option = confirm('Are you sure to delete this caregory?')
		if(!option) return

		$.post('{{ route('category-delete') }}', {
			'_token': '{{ csrf_token() }}',
			'id': id
		}, function(data) {
			location.reload()
		})
	}
</script>
@stop


#edit.blade.php


@extends('layouts.master')

@section('content')
<div class="container">
	<form method="post" action="{{ route('category-confirm-edit') }}">
		{{ csrf_field() }}
		<div class="form-group">
			<label>Category Name: </label>
			<input type="text" name="id" hidden value="{{ $category->id }}">
			<input type="text" name="name" class="form-control" value="{{ $category->name }}">
		</div>
		<div class="form-group">
			<button class="btn btn-success mt-2">Update Category</button>
		</div>
	</form>
</div>
@stop




Phản hồi từ học viên

5

(Dựa trên đánh giá ngày hôm nay)

Đăng nhập để làm bài kiểm tra

Chưa có kết quả nào trước đó