Laravel 使用数据库

Laravel使用数据库处理非常简单。Laravel目前支持以下4个数据库:

  • MySQL
  • Postgres
  • SQLite
  • SQL Server

可以使用原始SQL,流畅的查询构建器和Eloquent ORM来触发对数据库的查询。为了理解Laravel的所有CRUD(创建,读取,更新,删除)操作,我们将使用简单的学生管理系统。

 

连接到数据库

config/database.php 文件中 配置数据库, 并使用MySQL中的结构创建大学数据库,如下表所示。

数据库:College

表:student

列名称 列数据类型 额外
ID INT(11) 主键| 自动递增
名称 VARCHAR(25)  

我们将看到如何使用Laravel在学生表中添加,删除,更新和检索数据库中的记录。

 

插入记录

我们可以使用DB facade使用insert方法插入记录。insert方法的语法如下表所示。

Syntax bool insert(string $query, array $bindings = array())
Parameters
  • $query(string) − query to execute in database
  • $bindings(array) − values to bind with queries
Returns bool
Description Run an insert statement against the database.

 

实例

步骤1 - 执行以下命令以创建名为StudInsertController的控制器

php artisan make:controller StudInsertController --plain

第2步 - 成功执行第1步后,您将收到以下输出 -

插入记录

第3步 - 将以下代码复制到文件

app/Http/Controllers/StudInsertController.php

app/Http/Controllers/StudInsertController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class StudInsertController extends Controller {
   public function insertform(){
      return view('stud_create');
   }

   public function insert(Request $request){
      $name = $request->input('stud_name');
      DB::insert('insert into student (name) values(?)',[$name]);
      echo "Record inserted successfully.<br/>";
      echo '<a href = "/insert">Click Here</a> to go back.';
   }
}

步骤4 - 创建名为resources/views/stud_create.php的视图文件,并在该文件中复制以下代码。

resources/views/stud_create.php

<html>
   <head>
      <title>Student Management | Add</title>
   </head>

   <body>
      <form action = "/create" method = "post">
         <input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
         <table>
            <tr>
               <td>Name</td>
               <td><input type='text' name='stud_name' /></td>
            </tr>
            <tr>
               <td colspan = '2'>
                  <input type = 'submit' value = "Add student"/>
               </td>
            </tr>
         </table>
      </form>

   </body>
</html>

第5步 - 在app/Http/routes.php中添加以下行。

app/Http/routes.php

Route::get('insert','StudInsertController@insertform');
Route::post('create','StudInsertController@insert');

步骤6 - 访问以下URL以在数据库中插入记录。

http://localhost:8000/insert

步骤7 - 输出将如下图所示。

插入记录

 

查询记录

配置数据库后,我们可以使用select方法使用DB facade检索记录。select方法的语法如下表所示。

Syntax array select(string $query, array $bindings = array())
Parameters
  • $query(string) − query to execute in database
  • $bindings(array) − values to bind with queries
Returns array
Description Run a select statement against the database.

 

实例

步骤1 - 执行以下命令以创建名为StudViewController的控制器。

php artisan make:controller StudViewController --plain

第2步 - 成功执行第1步后,您将收到以下输出 -

查询记录

第3步 - 将以下代码复制到文件

app/Http/Controllers/StudViewController.php

app/Http/Controllers/StudViewController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class StudViewController extends Controller {
   public function index(){
      $users = DB::select('select * from student');
      return view('stud_view',['users'=>$users]);
   }
}

步骤4 - 创建名为resources / views / stud_view.blade.php的视图文件,并在该文件中复制以下代码。

resources/views/ stud_view.blade.php

<html>

   <head>
      <title>View Student Records</title>
   </head>

   <body>
      <table border = 1>
         <tr>
            <td>ID</td>
            <td>Name</td>
         </tr>
         @foreach ($users as $user)
         <tr>
            <td>{{ $user->id }}</td>
            <td>{{ $user->name }}</td>
         </tr>
         @endforeach
      </table>

   </body>
</html>

第5步 - 在app / Http / routes.php中添加以下行。

app/Http/routes.php

Route::get('view-records','StudViewController@index');

步骤6 - 访问以下URL以查看数据库中的记录。

http://localhost:8000/view-records

步骤7 - 输出将如下图所示。

查询记录

 

更新记录

我们可以使用更新方法使用DB facade更新记录。update方法的语法如下表所示。

Syntax int update(string $query, array $bindings = array())
Parameters
  • $query(string) − query to execute in database
  • $bindings(array) − values to bind with queries
Returns int
Description Run an update statement against the database.

 

实例

请注意以下示例以了解有关更新记录的更多信息 -

步骤1 - 执行以下命令以创建名为StudViewController的控制器。

php artisan make:controller StudUpdateController --plain

第2步 - 成功执行后,您将收到以下输出 -

更新记录

步骤3 - 将以下代码复制到文件app / Http / Controllers / StudUpdateController.php

app/Http/Controllers/StudUpdateController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class StudUpdateController extends Controller {
   public function index(){
      $users = DB::select('select * from student');
      return view('stud_edit_view',['users'=>$users]);
   }
   public function show($id) {
      $users = DB::select('select * from student where id = ?',[$id]);
      return view('stud_update',['users'=>$users]);
   }
   public function edit(Request $request,$id) {
      $name = $request->input('stud_name');
      DB::update('update student set name = ? where id = ?',[$name,$id]);
      echo "Record updated successfully.<br/>";
      echo '<a href = "/edit-records">Click Here</a> to go back.';
   }
}

第4步 - 创建一个名为的视图文件

resources / views / stud_edit_view.blade.php并在该文件中复制以下代码。

resources/views/stud_edit_view.blade.php

<html>
   <head>
      <title>View Student Records</title>
   </head>

   <body>

      <table border = "1">
         <tr>
            <td>ID</td>
            <td>Name</td>
            <td>Edit</td>
         </tr>
         @foreach ($users as $user)
         <tr>
            <td>{{ $user->id }}</td>
            <td>{{ $user->name }}</td>
            <td><a href = 'edit/{{ $user->id }}'>Edit</a></td>
         </tr>
         @endforeach
      </table>

   </body>
</html>

第5步 - 创建另一个名为的视图文件

resources / views / stud_update.php并在该文件中复制以下代码。

resources/views/stud_update.php

<html>

   <head>
      <title>Student Management | Edit</title>
   </head>

   <body>
      <form action = "/edit/<?php echo $users[0]->id; ?>" method = "post">
         <input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">

         <table>
            <tr>
               <td>Name</td>
               <td>
                  <input type = 'text' name = 'stud_name'
                     value = '<?php echo$users[0]->name; ?>'/>
               </td>
            </tr>
            <tr>
               <td colspan = '2'>
                  <input type = 'submit' value = "Update student" />
               </td>
            </tr>
         </table>

      </form>

   </body>
</html>

第6步 - 在app / Http / routes.php中添加以下行。

app/Http/routes.php

Route::get('edit-records','StudUpdateController@index');
Route::get('edit/{id}','StudUpdateController@show');
Route::post('edit/{id}','StudUpdateController@edit');

步骤7 - 访问以下URL以更新数据库中的记录。

http://localhost:8000/edit-records

步骤8 - 输出将如下图所示。

更新记录

步骤9 - 单击任何记录上的编辑链接,您将被重定向到可以编辑该特定记录的页面。

步骤10 - 输出将如下图所示。

更新记录

步骤11 - 编辑该记录后,您将看到如下图所示的提示。

更新记录

 

删除记录

我们可以使用delete方法使用DB facade删除记录。delete方法的语法如下表所示。

Syntax int delete(string $query, array $bindings = array())
Parameters
  • $query(string) − query to execute in database
  • $bindings(array) − values to bind with queries
Returns int
Description Run a delete statement against the database.

 

实例

步骤1 - 执行以下命令以创建名为StudDeleteController的控制器。

php artisan make:controller StudDeleteController --plain

第2步 - 成功执行后,您将收到以下输出

删除记录

第3步 - 将以下代码复制到文件

app/Http/Controllers/StudDeleteController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class StudDeleteController extends Controller {
   public function index(){
      $users = DB::select('select * from student');
      return view('stud_delete_view',['users'=>$users]);
   }
   public function destroy($id) {
      DB::delete('delete from student where id = ?',[$id]);
      echo "Record deleted successfully.<br/>";
      echo '<a href = "/delete-records">Click Here</a> to go back.';
   }
}

第4步 - 创建一个名为的视图文件

resources / views / stud_delete_view.blade.php并在该文件中复制以下代码。

resources/views/stud_delete_view.blade.php

<html>

   <head>
      <title>View Student Records</title>
   </head>

   <body>
      <table border = "1">
         <tr>
            <td>ID</td>
            <td>Name</td>
            <td>Edit</td>
         </tr>
         @foreach ($users as $user)
         <tr>
            <td>{{ $user->id }}</td>
            <td>{{ $user->name }}</td>
            <td><a href = 'delete/{{ $user->id }}'>Delete</a></td>
         </tr>
         @endforeach
      </table>

   </body>
</html>

第5步 - 在app / Http / routes.php中添加以下行。

app/Http/routes.php

Route::get('delete-records','StudDeleteController@index');
Route::get('delete/{id}','StudDeleteController@destroy');

步骤6 - 输出将如下图所示。

删除记录

步骤7 - 单击删除链接以从数据库中删除该记录。您将被重定向到一个页面,您将在该页面中看到如下图所示的消息。

删除记录

步骤8 - 单击“单击此处”链接,您将被重定向到一个页面,您将看到除已删除记录之外的所有记录。

删除记录

本章介绍Laravel项目中的错误和日志记录以及如何处理它们。 错误一个项目正在进行中,会产生一些错误。在启动新的Laravel项目时,已经为您配置了错误和异常处理。通常,在本地环境中,我们需要查看用于 ...