Laravel - Retrieve Records


Advertisements

After configuring the database, we can retrieve the records using the DB facade with select method. The syntax of select method is as shown in the following table.

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.

Example

Step 1 − Execute the below command to create a controller called StudViewController.

php artisan make:controller StudViewController --plain

Step 2 − After the successful execution of step 1, you will receive the following output −

StudViewController

Step 3 − Copy the following code to file

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]);
   }
}

Step 4 − Create a view file called resources/views/stud_view.blade.php and copy the following code in that file.

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>

Step 5 − Add the following lines in app/Http/routes.php.

app/Http/routes.php

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

Step 6 − Visit the following URL to see records from database.

http://localhost:8000/view-records

Step 7 − The output will appear as shown in the following image.

Id Name
laravel_working_with_database.htm
Advertisements