Controllers in Laravel 5.8

min read

Day 9 #100DaysOfCode

Trong bài viết hôm này mình tiếp tục tìm hiểu về Controllers(bộ điều khiển) trong Laravel 5.8 , ở các bài viết trước mình đã đi qua về cách cài đặt, cũng như cấu hình Route(bộ định tuyến) trong Laravel. Các bạn có thể xem lại tại đây 

+ Create Project Laravel 5.8 using Composer
+ Route in Laravel 5.8

Trong Laravel, tất cả các file Controller đa phần điều nằm trong App/Http/Controllers 
Tạo một Controller, ta sử dụng câu lệnh cmd Artisan như sau:

php artisan make:controller TasksController 
//or
php artisan make:controller TasksController --resource 

Nếu bạn gắn thêm  --resource phía sau. Laravel sẽ tạo cho ta cấu trúc file có các function như : (index,create,store,show,edit,update,destroy)
Okay, sao khi tạo xong, bạn sẽ được một file TasksController.php trong thư mục App\Http\Controllers

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class TasksController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * 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)
    {
        //
    }

    /**
     * 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)
    {
        //
    }
}

Okay, ta sẽ cập nhật lại function index() trong TasksController.php , và routes/web.php

// App\Http\Controllers
public function index()
{
    return 'Hello, World!';
}

// routes/web.php
Route::get('/', 'TasksController@index');

Bạn kiểm tra đường dẫn sao : http://localhost/laravel58, xem có hiện thông báo  "Hello, World!" không nhé

Đồng thời ta có thể chỉnh sửa cho function index() gọi tới template blade như sau:

using App\Task;
public function index()
{
    return view('tasks.index')->with('tasks', Task::all());
}  

Nó sẽ return về template index.blade.php trong thư mục resources/views/tasks/index.blade.php hoặc resources/views/tasks/index.php, và chuyền cho nó biến "tasks",chứa thông tin toàn bộ data được trả về từ Task::all()
Bạn sẽ hỏi Task đến từ đâu? Task nó là một model, bạn có thể tạo Task.php trong thư mục App. Task tượng chưng cho một table "Tasks" trong database, vì thế ta có thể dùng cú pháp Eloquent truy vấn các phương thức như : create(),update(),delete(),get(),getAll(),all(),...
Để dùng được Task.php, ta cần using App\Task trong  file Controller
Okay tiếp tục trong template index.blade.php bạn có thể foreach data nó ra như thế này

@foreach($tasks as $task)
    {{$task->title}}
@endforeach

Okay, ta tìm hiểu thêm một số function trong Controller tiếp theo thôi
Hãy cập nhật function store() lại như dưới đây, ta cần phải thêm một dữ liệu task vào database 

// TasksController.php
using App\Task;
public function store(\Illuminate\Http\Request $request)
{
    Task::create($request->only(['title', 'description']));
    return redirect('tasks');
}

Code trên ta chỉ định rằng, tôi chỉ muốn thêm dữ liệu cho cột "title" & "description" 
Hoặc bạn có thể thiếp lập giá trị mặc định như dưới đây

Task::create([
    'title' => 'Buy milk',
    'description' => 'Remember to check the expiration date this time, Norbert!',
]);

Thiếp lập Route gọi tới function store() như sau:

// routes/web.php 
Route::get('tasks/create', 'TasksController@create'); //redirect đến template create.blade.php 
Route::post('tasks', 'TasksController@store'); // submit form method ="POST", add record Task

Trong Laravel đã có thêm tính năng Resource Controller, đã thiếp lập các chức năng CRUD(create, read, update, delete) trong Controller khi ta tạo file Controller , đồng thời Laravel đã thiết lặp sẵn route cho ta

php artisan make:controller ProductsController --resource

Add route resource trong routes/web.php

Route::resource('products', 'ProductsController');

Sau khi add xong, chạy lệnh artisan dưới đây, sẽ show tất cả các route của ta

php artisan route:list 

Laravel rất hay đã thiết lặp sẵn cấu trúc Route cho ta, còn đối với việc bạn đang muốn thiết lập Route cho API thì bạn có thể dùng như sau:
Tạo file ApiController.php trong thư mục App\Http\Controllers

php artisan make:controller PostsController --api 

Add route resource trong routes/api.php

Route::apiResource('posts', 'PostsController');

Chạy lệnh php artisan route:list , sẽ được list route như dưới đây 

Controllers in Laravel 5.8

Với các bước như trên bạn sẽ ít tốn thời gian thiết lặp Route cho từng chức năng
Route::resource('products', 'ProductsController'); đã bao gồm các phương thức (POST,GET,DELETE,PATCH,PUT), tiện lợi rất nhiều khi ta thiệp lập Route

Okay, ở đây mình muốn chia sẻ thêm, sẽ có lúc trong ứng dụng của bạn, chỉ thực hiện một nhiệm vụ. khi đó bạn có thể chỉ định một Route thực hiện một nhiệm vụ trong Controller mà không cần chú ý đến cách đặt tên phương thức
Bạn sẽ dùng _invoke() trong PHP, nó cho phép gọi "invoke" của một lớp(class), coi nó như một function và gọi nó thôi
Nó là một công cụ mà Laravel cho phép chúng ta trỏ tới một Route, bạn có thể thực hiện nó như dưới đây 

Tạo một lớp VoteController trong App\Http\Controllers

php artisan make:controller VoteController --invokable
// App\Http\Controllers 
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class VoteController extends Controller
{
    /**
     * Handle the incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function __invoke(Request $request)
    {
        // Update Vote 
        //.....
        return Response()->json(["success"=>$request->all()]);
    }
}

resources/views/login.blade.php 

@extends("main")
@section('content')
<form action="{{route('login')}}" method="post">
    @csrf
    <input type="text" name="email" />
    <input type="text" name="name" />
    <input type="submit" value="login" />

</form>
@endsection

routes/web.php 

Route::get('/login',function(){
    return view('login');
});
Route::post('Login/update-avatar', 'VoteController')->name("login");

Okay, mình tìm hiểu nhiêu đây thôi, từ từ có gì tìm hiểu tiếp kaka

x

Ủ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!)