Skip to main content

Database connection in Laravel

Database connection in Laravel

Database connection establishing and getting data from DB

In these notes, you can understand establishing a DB connection and retrieving data from DB.
Last previous notes, we made blog post data by hard coding, now fetching data from MySQL database.
Here I have created a MySQL database and table for blogs.

Now I am going to add MySQL database configuration in Laravel. As we discussed on early notes we should config DB in .ENV file


DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=mylaravel
DB_USERNAME=root
DB_PASSWORD=
After this setup, I need to write a method in my controller to fetch data from DB.

Example 1

Getting data from DB, This is simple getting data from DB. I used use DB; class and I written direct query.


<?php

	namespace App\Http\Controllers;

	use Illuminate\Http\Request;
	use DB;

	class BlogController extends Controller
	{
		/* Below as example of getting data from DB */
		public function blog_db_example($slug)
		{

			$post = DB::table('tbl_blogs')->where('slug',$slug)->first();

			if(!$post)
			{
				abort(404);
			}

			return view('blog_from_db',["blog"=>$post]);
		}
	}

Example 2

Using models, Laravel has Eloquent feature.

You can create a model using PHP artisan commands

php artisan make:model model_name

<?php

	namespace App\Http\Controllers;

	use Illuminate\Http\Request;
	use App\Models\Tbl_blogs;

	class BlogController extends Controller
	{

		 /* Below as example of getting data from Model */
		 public function blog_db_model_example($slug)
		 {
			return view('blog_from_db',[
				"blog" => Tbl_blogs::where('slug',$slug)->firstOrFail()
				]);
		 }
	}
In my view, I simple print the blog_desc


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h3>Welcome to Blog posts from laravel</h3>
    <p>{{$blog->blog_desc}}</p>
</body>
</html>
and in web.php


/**
 * Example of bring blog data from db
 */
Route::get('blog_from_db_example/{post}','App\Http\Controllers\BlogController@blog_db_example');

/**
 * Example of bring blog data from db
 */
Route::get('blog_from_model_db_example/{post}','App\Http\Controllers\BlogController@blog_db_model_example');
Result same as we expected

Comments

Popular posts from this blog

Laravel Commands

Laravale commands #Check route list php artisan route:list #Check upload files links php artisan storage:link #Check database connected or not php artisan db #Make Request file php artisan make:request YourNameRequest #Make Controller #(In this statement you used -r -> resources and -m -> model. It will create CustomersController and Customers Model files) php artisan make:controller CustomersController -r -m Customers #Make Resource file php artisan make:resource CustomersResource #To check migration files status that those files are running or not with below commands php artisan migrate:status #To check if there is any pending migrate files to run #(also this command shows us the mysql query before running migration file) php artisan migrate --pretend #To make a database table (in this example Products name as taken) php artisan make:migration create_products_table #To create a Request file php artisan make:request StoreProductRequest php artisan make:request Up...

Mysql columns creation in laravel

List of columns  $table->id(); // increment value $table->string('title')->comment('this is blog title'); $table->string('slug')->unique(); $table->text('short_desc'); $table->longText('description'); $table->boolean('is_published')->default(false); $table->integer('min_of_read')->nullable(true); $table->enum('status', ['Active', 'Inactive']); $table->float('discount'); $table->smallInteger('type_id'); $table->date('start_date')->nullable(); $table->timestamps(); $table->foreign('created_by')->references('id')->on('users'); // introducing foreign key $table->unsignedBigInteger('user_id'); //? $table->decimal('latitude', 9, 6)->nullable(true); // Let's say you want starting value from 1000 $table->id()->from(1000); // increment value start from 1000 ->nullabl...

Laravel form validations

 Laravel Validations: List of types "first_name" => 'required|alpha:ascii|min:3|max:100',// alpha:ascii (only accepts a-z) "middle_name" => 'string', "last_name" => 'required|string', "email" => 'required|email|unique:users,email', "password" => 'required|string|confirmed', "sex" => 'required|string', "phone_no" => 'required|string', "account_type" => 'required|string', "dob" => 'required|date_format:d-m-Y', // date with format "nationality" => 'required|string', "company" => 'required|string', "company_sector" => 'required|string', "company_address" => 'required|string' "bank_account_no" => 'required|min_digits:3|max_digits:5', "role" => 'required|in:admin,editor,viewer', ...