Storing and retrieving data from database tables using eloquent in Laravel and sending to views.

Mubasheer Shaik
May 31, 2019 · 3 min read

In this example, we are going to create a contacts table inside our project Mysql database using Laravel migrations and we will store and fetch data from it using eloquent.

Pre-requisites: I assume that you have a knowledge of installing Laravel project and running it on the local host and creation of the database.

Let’s start

php artisan make:model Contact -cm

The above command will create a Model named Contact and options “-cm” creates a controller “ContactController” and migration.

Find migration under database/migrations:

Creating two fields in the contacts table with type varchar (string here gives varchar in mysql).

Run command to create table with the mentioned fields.

Now, you have “contacts” table in your database.

Open “ContactController” created under App/Http/Controllers/

Also, create the view file name “listContact.blade.php” under “resources/views” folder.

Go to “Contact.php” model created for contact and place the code in it:

Contact model created
namespace App;
use Illuminate\Database\Eloquent\Model;class Contact extends Model
protected $fillable = [
'contact_name', 'contact_email'
protected $hidden = [
'created_at', 'updated_at',

The above code is essential to mass save and update.

Place code in the controller to store the data to the contacts table.

class ContactController extends Controller{public function storeContact(Request $request){// validation goes here$contact = Contact::create($request->all());return $contact;}public function getAllContacts(){$contacts = Contact::all();//if you want to get contacts on where condition use below code//$contacts = Contact::Where('tenant_id', "1")->get();
return view('listContact', compact('contacts'));

In the above code, the method “storeContact” is to store the data to contacts table and method “getAllContacts” is to get all contacts data from the database table return to the view “listContact.blade.php”.

Routes in routes/web.php :

Route::post('/CreateContact', 'ContactController@storeContact');
Route::get('/getContacts', 'ContactController@getAllContacts');

In view “listContact.blade.php” you can get all contacts by simply placing the returned data:

{{ $contacts }}

listContact.blade.php : Displaying all contacts inside the select box,

Hope this helps, Happy coding!!

More From Medium

More from Mubasheer Shaik

Related reads

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade