Laravel - hands on Implementation - add, delete, modify and query

Posted by jvanv8 on Thu, 23 Apr 2020 06:06:46 +0200

Get a framework, in addition to understanding the framework, but also to achieve the basic CURD operation.

Add to

1. Configure route, specify add page;

// Add the following in routes/web.php:
// Add page and storage path Laravel7/resources/views/Users/add.blade.php
// The view file ends with. blade.php by default
Route::get('/add', function(){
    return view('Users.add');
});

2. Create and edit the add view page;

<!-- View file storage path Laravel7/resources/views/Users/add.blade.php -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add to</title>
</head>
<body>
    <form action="regDo" method="post">
        <div>
            <span>user name</span>
            <span><input type="text" name="name" id=""></span>
        </div>
        <div>
            <span>Password</span>
            <span><input type="text" name="pwd" id=""></span>
        </div>
        <div>
            <span></span>
            <span><input type="submit" value="register"></span>
        </div>
        <!-- If yes POST The way to submit data, need to add csrf protect -->
        <!-- Location: Official manual -> Basic functions -> csrf protect -->
        {{ csrf_field() }}
    </form>
</body>
</html>

3. Configure the route binding controller and method to perform the add operation;

// Add the following in routes/web.php:
// post submission method and method of form in view layer
// doAdd submission address, action of form in view layer
Route::post('/doAdd', 'UsersController@doAdd');

4. Receive data in the controller, call the model layer to perform the add operation, return success or failure;

Method in controller:

/**
 * Add to
 * @param Request 
 * @return string
 */

public function create(Request $request)
{
    // Get data to submit
    $data['name'] = $request->input('name', '');
    $data['pwd'] = $request->input('pwd', '');
    // Call model layer method to add data
    $res = Users::addOne($data);
    // Judge whether it is added successfully
    if (!$res) {
        // Note: the a tag's href attribute is the specified route
        return 'Add failed!! Jump to<a href="/add">Add page</a>';
    }
    return 'Successfully added!! Jump to<a href="/show">Display page</a>';
}

Methods in the model layer:

// Note: the model layer needs to specify the data table name associated with the model
// protected $table = 'users';

/**
 * Add a piece of data
 * @param array $data 
 * @return booler
 */

public static function addOne($data)
{
    return self::insert($data);
}

Exhibition

1. Configure the route binding controller and method to obtain the data to be displayed;

// Add the following in routes/web.php:
// Show data
Route::get('/show', 'UsersController@show');

2, call the model layer to execute query operation in the controller, then judge whether success or success call the view layer to display the data and fail to return the failure.

Methods in the controller:

/**
 * Exhibition
 */

public function show()
{
    // Call method in model layer to get data
    $res = Users::getAll();
    // Judge whether it is successful
    if (!$res) {
        return 'There is no data in the database!!';
    }
    // Successfully send data to view file through view method
    return view('Users.show', ['res' => $res]);
}

Methods in the model layer:

/**
 * Get all the data
 * @return array
 */

public static function getAll()
{
    return self::get();
}

3. Edit the view layer file and show the data through foreach;

<!-- View file storage path Laravel7/resources/views/Users/show.blade.php -->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Exhibition</title>
</head>

<body>
    <div>
        <span> Exhibition </span>
        <span> <a href="/page">Pagination display</a> </span>
    </div>
    <table>
        <tr>
            <td>ID</td>
            <td>NAME</td>
            <td>PWD</td>
            <td>STATUS</td>
            <td>LAST LOGIN</td>
        </tr>
        <!-- Manual: front end development -> blade Template -> loop  -->
        @foreach ( $res as $v )
        <tr>
            <td>{{ $v->id }}</td>
            <td>{{ $v->name }}</td>
            <td>{{ $v->pwd }}</td>
            <td>{{ $v->status }}</td>
            <td>{{ $v->last }}</td>
        </tr>
        @endforeach
    </table>
</body>

</html>

Pagination display

1. Configure the route binding controller and method to obtain the data to be displayed;

// Add the following in routes/web.php:
// Show data
Route::get('/page', 'UsersController@page');

2, call the model layer to execute the query operation in the controller, then judge whether it is successful.

Method in controller:

/**
 * Pagination display 
 */

public function page()
{
    // Call method in model layer to get data
    $res = Users::page();
    // Judge whether it is successful
    if (!$res) {
        return 'There is no data in the database!!';
    }
    // Successfully send data to view file through view method
    return view('Users.page', ['res' => $res]);
}

Method in model layer:

/**
 * Pagination display
 * @return array
 */

public static function page()
{
    // The paginate method automatically sets limits and offsets based on the page the user is viewing
    // 5 is the number of items displayed per page
    return self::paginate(5);
}

3. Edit the view layer file and show the data through foreach;

<!-- View file storage path Laravel7/resources/views/Users/page.blade.php -->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pagination display</title>
    <!-- Laravel The default style for frames is BootStrap,In order to display and beautify in pages, so reference css style -->
    <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.4/css/bootstrap.min.css">
</head>

<body>
    <div>
        <span> Pagination display </span>
        <span> <a href="/show">General display</a> </span>
    </div>
    <table class="table" style="text-align: center">
        <tr>
            <td>ID</td>
            <td>NAME</td>
            <td>PWD</td>
            <td>STATUS</td>
            <td>LAST LOGIN</td>
            <td>ACTION</td>
        </tr>
        <!-- Manual: front end development -> blade Template -> loop  -->
        @foreach ( $res as $v )
        <tr>
            <td>{{ $v->id }}</td>
            <td>{{ $v->name }}</td>
            <td>{{ $v->pwd }}</td>
            <td>{{ $v->status }}</td>
            <td>{{ $v->last }}</td>
            <td>
                <a href="upd?id={{ $v->id}}">modify</a>
                <a href="del?id={{ $v->id}}">delete</a>
            </td>
        </tr>
        @endforeach
        <tr>
            <td colspan="6">
                <!-- Manuals: Databases -> paging -> Show paging results -->
                {{ $res->links() }}
            </td>
        </tr>
    </table>

</body>

</html>

delete

1. Add delete link in the displayed view file to specify the deleted route;

Edit the displayed view file

// Add delete link to view file
// del route to delete
<a href="del?id={{ $v->id}}">delete</a>

Edit route file:

// Add the following to the route file to delete the route
Route::get('/del', 'UsersController@del');

2. When the controller receives the data, it calls the model to perform the deletion operation, and then judges whether it is successful or not. If it is successful, it returns success. If it fails, it returns failure;

Method in controller:

/**
 * delete
 */

public function del(Request $request)
{
    // Receive data ID
    $where['id'] = $request->input('id', 0 );
    // Call the delete method in the model layer
    $res = Users::del($where);
    // Judge execution result
    if (!$res) {
        return 'Delete failed!! Jump to<a href="/page">Display page</a>';
    }
    return 'Delete succeeded!! Jump to<a href="/page">Display page</a>';
}

Method in model layer:

/**
 * delete
 * @param array $where
 * @return booler
 */

public static function del($where)
{
    return self::where($where)->delete();
}

modify

1. Add modification link in the displayed view file to specify the route to get the data to be modified;

Edit the displayed view file

// Add modification link in view file
// Routes modified by upd
<a href="upd?id={{ $v->id}}">modify</a>

Edit route file:

// Add the following to the route file to delete the route
Route::get('/upd', 'UsersController@upd');

2. The controller receives the data, calls the model to obtain the data, and then sends the data to the view file;

Method in controller:

/**
 * Get the data to be modified
 */

public function upd(Request $request)
{
    // Receive data ID
    $where['id'] = $request->input('id', 0);
    // Call the method in the model layer to get a piece of data
    $res = Users::getOne($where);
    // Judge execution result
    if (!$res) {
        return 'Data acquisition failed!! Jump to<a href="/page">Display page</a>';
    }
    // Successfully send data to view file through view method
    return view('Users.upd', ['res' => $res]);
}

Method in model layer:

/**
 * Query a piece of data
 * @param array $where
 * @return array
 */

public static function getOne($where)
{
    // return self::where( $where )->first();
    return self::firstWhere($where);
}

3. Display the data sent to the modification page;

<!-- View file storage path Laravel7/resources/views/Users/upd.blade.php -->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>modify</title>
</head>

<body>

    <form action="doUpd" method="post">
        <div>
            <span>user name</span>
            <span><input type="text" name="name" id="" value="{{ $res->name }}"></span>
        </div>
        <div>
            <span>Password</span>
            <span><input type="text" name="pwd" id="" value="{{ $res->pwd }}"></span>
        </div>
        <div>
            <span><input type="hidden" name="id" value="{{ $res->id }}"></span>
            <span><input type="submit" value="modify"></span>
        </div>
        <!-- Location: Official manual -> Basic functions -> csrf protect -->
        {{ csrf_field() }}
    </form>
</body>

</html>

4. Configure the route binding controller and method to perform modification;

// Execute modification
// post submission method and method of form in view layer
// doUpd submit address, action of form in view layer
Route::post('/doUpd', 'UsersController@doUpd' );

5. When the controller receives the data, it calls the model to perform the modification operation, and then judges whether it is successful. If it is successful, it will return success. If it fails, it will return failure;

Method in controller:

/**
 * Execute modification
 */

public function doUpd(Request $request)
{
    // Receive data ID as modification condition
    $where['id'] = $request->input('id', 0);
    // Receive other data as data to be modified
    $data['name'] = $request->input( 'name', '' );
    $data['pwd'] = $request->input( 'pwd', '' );
    // Call the modification method in the model layer
    $res = Users::upd( $where, $data );
    // Judge execution result
    if (!$res) {
        return 'Modification failed!! Jump to<a href="/page">Display page</a>';
    }
    return 'Modification succeeded!! Jump to<a href="/page">Display page</a>';
}

Method in model layer:

/**
 * modify
 * @param array $where
 * @param array $data
 * @return booler
 */

public static function upd($where, $data)
{
    return self::where($where)->update($data);
}

Common errors

1,Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException No message

Specific screenshot:

Solution: check whether the request mode of route is consistent with that of submission.

2,Illuminate \ Database \ QueryException (42S02)

Specific screenshot:

Resolution: see if the model layer specifies the data table associated with the model

Topics: PHP Database Attribute Laravel