Fetching data from the Database using Laravel

  • Post author:
  • Post category:Laravel
  • Post comments:1 Comment
  • Post last modified:October 5, 2020
  • Reading time:3 min(s) read

In this particular blog, I’m going to discuss, Fetching data from the Database using Laravel. If you are new here I will suggest you check all the Laravel related articles for better understanding.

So, to learn Fetching data from the Database using Laravel, I hope you have seen our previous videos and blogs of the Laravel series.

Step-1: Create a blade(example.blade.php) where you want to show your data. Find the code given below:

@extends('master')
@section('content')
<br> 
<div class="container">
<div class="card">
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
<th>Sl. No.</th>
<th>Name</th>
<th>Email</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<?php 
$sl=1;

foreach ($data as $key) {
?>
<tr>
<td>{{ $sl++ }}</td>
<td>{{ $key->name }}</td>
<td>{{ $key->email }}</td>
<td>{{ $key->address }}</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
</div>

@stop
Step-2: Create a function to your respective controller as shown in the below code.
public function fetch()
      {
        $fetch_data= App\Emp_model::all()->sortByDesc('id');
        $capsule = array('data' =>$fetch_data);
        return view('show')->with($capsule);
      }  

In the above block of code $fetch_data= App\Emp_model::all()->sortByDesc(‘id’) used to fetch all data from the respective table in descending  order and store in $fetch_data variable. After that an array has been used to encapsulate the fetched data.

The complete code of controller and model files are given below:

Controller(Employee.php):

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App;
class Employee extends Controller
{
public function home($value='')
{
return view('a');
}

public function xx()
{
return view('about');
}

//first create a view form.

public function registration($value='')
{
return view('registration');
}

//Now create a function to insert data into database

public function data_insert(Request $r) //Request is a method and $r is it's object
{
$name=$r->uname;
$email=$r->uemail;
$address=$r->uadd;
$users= new App\Emp_model;
$users->name=$name;
$users->email=$email;
$users->address=$address;

$insert=$users->save();
if($insert){
return redirect('/reg')->with('success','Data added successfully!');
}
}

public function fetch()
{
$fetch_data= App\Emp_model::all()->sortByDesc('id');
$capsule = array('data' =>$fetch_data);
return view('show')->with($capsule);
}     

}

Model(Emp_model.php):

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Emp_model extends Model
{
   //set your table name here
   protected $table="users";
}

This Post Has One Comment

  1. Somnath Bhunia

    It’s very Helpful.

Leave a Reply