CodeIgniter Laravel PHP Example HTML Javascript jQuery MORE Videos New

Retrieve data from database using Laravel framework


In this example we will discuss about how to retrieve a record or data from MySQL database using laravel framework PHP.

For retrieve data from MySQL database using laravel framework first we have to create a table in data base.

After create a table in the MySQL database you need to insert record or data on it.If you want to know how to insert data in laravel framework please visit the link : Insert data in Laravel.

The SELECT statement is used to retrieve data from one or more tables:

The SQL query for retrieve specific column.

SELECT column_name(s) FROM table_name

or we can use the * character to retrieve ALL columns from a table:

SELECT * FROM table_name

To learn more about SQL, please visit our SQL tutorial.

Create 3 files for retrieve data in Laravel :

  • StudViewController.php (app/Http/Controllers/StudViewController.php)
  • stud_view.blade.php (resources/views/stud_view.blade.php)
  • web.php (routes/web.php)

In this example we retrieve the students data.

stud_view.blade.php

<!DOCTPE html>
<html>
<head>
<title>View Student Records</title>
</head>
<body>
<table border = "1">
<tr>
<td>Id</td>
<td>First Name</td>
<td>Last Name</td>
<td>City Name</td>
<td>Email</td>
</tr>
@foreach ($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->first_name }}</td>
<td>{{ $user->last_name }}</td>
<td>{{ $user->city_name }}</td>
<td>{{ $user->email }}</td>
</tr>
@endforeach
</table>
</body>
</html>

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_details');
return view('stud_view',['users'=>$users]);
}
}

web.php

<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
//retrive data
Route::get('view-records','StudViewController@index');

After fetch data the table look like this.

Id first name last name City name Email Id
1 Divyasundar Sahu Mumbai divyasundar@gmail.com
2 Hritika Sahu Pune hritika@gmail.com
3 Milan Jena Chennai milanjena@gmail.com