Laravel 5 Tutorial : How to Connect Database in laravel 5.3

Laravel 5 Tutorial for beginners : how to create connection / connect to database in Laravel 5.3? How to working and configure database in Laravel for beginners.

Laravel 5 Tutorial - Working with databases in Laravel 5.3 is very simple, we can create a connection to any databases like MySQL databases, SQLite, SQL Server, and Postgres. In Laravel currently support just for 4 database above.

Please Read :
  1. What's New in Laravel 5.3?
  2. How to use Middleware in Laravel
In the Laravel Default Connection directory is at app\config\database.php

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | PDO Fetch Style
    |--------------------------------------------------------------------------
    |
    | By default, database results will be returned as instances of the PHP
    | stdClass object; however, you may desire to retrieve records in an
    | array format for simplicity. Here you can tweak the fetch style.
    |
    */

    'fetch' => PDO::FETCH_OBJ,

    /*
    |--------------------------------------------------------------------------
    | Default Database Connection Name
    |--------------------------------------------------------------------------
    |
    | Here you may specify which of the database connections below you wish
    | to use as your default connection for all database work. Of course
    | you may use many connections at once using the Database library.
    |
    */
    // you can see, default db connection is using MySQL
    // you can change it with other databases
    'default' => env('DB_CONNECTION', 'mysql'),

    /*
    |--------------------------------------------------------------------------
    | Database Connections
    |--------------------------------------------------------------------------
    |
    | Here are each of the database connections setup for your application.
    | Of course, examples of configuring each database platform that is
    | supported by Laravel is shown below to make development simple.
    |
    |
    | All database work in Laravel is done through the PHP PDO facilities
    | so make sure you have the driver for your particular database of
    | choice installed on your machine before you begin development.
    |
    */

    'connections' => [

        'sqlite' => [
            'driver' => 'sqlite',
            'database' => env('DB_DATABASE', database_path('database.sqlite')),
            'prefix' => '',
        ],

        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '3306'),
            'database' => "env('DB_DATABASE', 'forge')",
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],

        'pgsql' => [
            'driver' => 'pgsql',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '5432'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'schema' => 'public',
            'sslmode' => 'prefer',
        ],

    ],

    /*
    |--------------------------------------------------------------------------
    | Migration Repository Table
    |--------------------------------------------------------------------------
    |
    | This table keeps track of all the migrations that have already run for
    | your application. Using this information, we can determine which of
    | the migrations on disk haven't actually been run in the database.
    |
    */

    'migrations' => 'migrations',

    /*
    |--------------------------------------------------------------------------
    | Redis Databases
    |--------------------------------------------------------------------------
    |
    | Redis is an open source, fast, and advanced key-value store that also
    | provides a richer set of commands than a typical key-value systems
    | such as APC or Memcached. Laravel makes it easy to dig right in.
    |
    */

    'redis' => [

        'cluster' => false,

        'default' => [
            'host' => env('REDIS_HOST', 'localhost'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', 6379),
            'database' => 0,
        ],

    ],

];

How to Configure Connection using MySQL Databases?

'mysql' => [
            'driver' => 'mysql', // your database that used
            'host' => 'localhost', // your server host
            'port' => '3306', // port number
            'database' => 'YOUr_DATABASE', // your database name
            'username' => 'DB_USERNAME', // your user id
            'password' => 'DB_PASSWORD', // your password
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],

You can see at the above that is a configure connecting laravel using MySQL database, but it's not recomended, you can doing to configure your database at .ENV file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=yourdatabasename
DB_USERNAME=root
DB_PASSWORD=yourpassword

You can configure your database in .ENV file, so don't change anything at the app\config\database.php.

How to Connect Database in laravel 5.3

Interaction to the Database

Laravel provides three ways to interact with the database :
  1. Raw Query
  2. Query Builder
  3. Eloquent ORM

Raw Query

To make a query to databases, you can use DB Class, an please configure with your database configurations.

// select query
$posts = DB::select('select * from yourtable');
foreach ($posts as $post) {
    echo $post->title . '<br>';
}

// select query with parameter
$posts = DB::select('select * from yourtable where yourfield = ?', array('somevalue'));
foreach ($posts as $post) {
    echo $post->title . '<br>';
}

// insert
DB::update('insert into yourtable(yourfield1, yourfield2) values (?, ?)', array('New article', 'this is just new article'));

// update
DB::update('update yourtable set yourfield1 = ? where yourfield2 = ?', array('update new article', 4));

// delete
$deletedCount = DB::delete('delete from yourtable where yourfield2 = 0');
echo $deletedCount;

// general statement
DB::statement('alter table yourtable add column created datetime null');

// transaction
DB::transaction(function(){
    ...query 1
    ...query 2
});

Query Builder

using Query builder to integrated with database make you enjoyed and more simple than using Raw Query.

// select multiple row
$posts = DB::table('yourtable')->get();
foreach ($posts as $post) {
    echo $post->title . '<br>';
}

// just select for one row
$post = DB::table('yourtable')->where('field1', 1)->first();

// selecting certain column
$post = DB::table('yourtable')->select('field1', 'title')->where('field1', 1)->first();
// ekivalen with next query
//$post = DB::table('yourtable')->select(array('field1', 'title'))->where('field1', 1)->first();

// just select one column
$lastArticleTitle = DB::table('yourtable')->orderBy('field1', 'desc')->pluck('title');
echo 'This Last Article Title: ' . $lastArticleTitle . '<br>';

$query = DB::table('yourtable')->addSelect('field1');
$query->addSelect('title');
$query->where('field2', 'publish');
$query->where('field1', '>', 1);

$posts = $query->get();

$posts = DB::table('yourtable')->skip(1)->take(1)->get();

ORM (Object Relational Mapper)

ORM is maping the query results from the database into the shape of objects we defined earlier. Form we define this previously referred to by Model (from MVC).

// Delete one row from object
$post = Post::find(2);
$post->delete();

// delete may rows once
Post::where('status', 'draft')->delete();

Video Tutorial Laravel : Working With Databases



See you next Lessons ...........

COMMENTS

Next Recomended


Feel free to code it up and send us a pull request.

Hi everyone, let's me know how much this lesson can help your work. Please Subscribe and Follow Our Social Media 'kodeajaib[dot]com' to get Latest tutorials and will be send to your email everyday for free!, Just hit a comment if you have confused. Nice to meet you and Happy coding :) all ^^



Follow by E-Mail


Name

ADO.NET,3,Ajax,6,Android,9,AngularJS,4,ASP.NET,4,Blogger Tutorials,7,Bootstrap,7,C++,1,Codeigniter,2,Cplusplus,6,Crystal Report,6,CSharp,25,Ebook Java,2,FlyExam,1,FSharp,3,Game Development,2,Java,35,JDBC,2,Laravel,84,Lumen,2,MariaDB,2,Ms Access,3,MySQL,31,ODBC,6,OleDB,1,PHP,14,PHP Framework,5,PHP MYSQLI,9,PHP OOP,5,Python,8,Python 3,4,SQL Server,4,SQLite,4,Uncategorized,5,Vb 6,2,Vb.Net,89,Video,48,Vue Js,4,WPF,2,Yii,3,
ltr
item
KODE AJAIB: Laravel 5 Tutorial : How to Connect Database in laravel 5.3
Laravel 5 Tutorial : How to Connect Database in laravel 5.3
Laravel 5 Tutorial for beginners : how to create connection / connect to database in Laravel 5.3? How to working and configure database in Laravel for beginners.
https://3.bp.blogspot.com/-bHCBpTNGM24/V8Hszla0zcI/AAAAAAAACV4/0fx2aQRnEkcqzsb3MdgSvtFLvORoGP_MgCLcB/s320/laravel-tutorial-for-beginner.png
https://3.bp.blogspot.com/-bHCBpTNGM24/V8Hszla0zcI/AAAAAAAACV4/0fx2aQRnEkcqzsb3MdgSvtFLvORoGP_MgCLcB/s72-c/laravel-tutorial-for-beginner.png
KODE AJAIB
https://www.kodeajaib.com/2016/08/tutorial-how-to-connect-database-laravel-53.html
https://www.kodeajaib.com/
https://www.kodeajaib.com/
https://www.kodeajaib.com/2016/08/tutorial-how-to-connect-database-laravel-53.html
true
3214704946184383982
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS CONTENT IS PREMIUM Please share to unlock Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy