Showing posts with label laravel 8. Show all posts
Showing posts with label laravel 8. Show all posts

Monday, 5 April 2021

Laravel 8 Tutorial - Join Multiple Table using Eloquent Model


In this post, we have share tutorial on How to join multiple tables using Eloquent Model in Laravel framework and then after fetch data from multiple table and display on web page in HTML table format. So in this post you will find the solution of how to fetch data from multiple table by join multiple table using Eloquent Model under this Laravel framework. In this post we will use inner join for fetch data data from multiple table using Eloquent join table relationship. So by using this tutorial, you can learn How to retrieve data from multiple tables using join multiple table with eloquent model relationship in single query run under this Laravel 8 framework.

So If you want to learn How to Join Multiple Tables in Laravel framework using Eloquent Model relationship then this post will help you, because in this post you can find step by step guide for implement how can we implement inner join for multiple tables join using Eloquent model under this Laravel framework. Under this post we have use Eloquent model in place of simple Laravel join, this is because Laravel Eloquent model is more effective that simple Laravel join while we have to fetch data from multiple table in single query. So for this here we have use Eloquent model for join multiple table in Laravel framework. Below you can find step by step guide for how to join multiple table using Laravel eloquent model.


Laravel 8 Tutorial - Join Multiple Table using Eloquent Model

  • Download Laravel Framework
  • Make Database connection
  • Create Model Class
  • Create Controller Class
  • Create View Blade file
  • Set Route
  • Run Laravel Server

Download Laravel Framework


For download fresh copy of Laravel framework, so first we have to into command prompt and run following command. This command will make join_table directory and under that directory it will download Laravel framework latest version.


composer create-project --prefer-dist laravel/laravel join_table


Make Database connection


After download and install Laravel framework and after this we want to make first database connection. So for make database connection, we have to open .env file and under this file, we have to define mysql database configuration. So it will create database connection in Laravel framework.


DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=testing
DB_USERNAME=root
DB_PASSWORD=


Once you have make database connection, then after we have to make table in mysql database. So for this you have to run following sql script in your local database, so it will create table in your define mysql database.


--
-- Table structure for table `city`
--

CREATE TABLE `city` (
  `city_id` int(11) NOT NULL,
  `state_id` int(11) NOT NULL,
  `city_name` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `city`
--

INSERT INTO `city` (`city_id`, `state_id`, `city_name`) VALUES
(1, 1, 'New York city'),
(2, 1, 'Buffalo'),
(3, 1, 'Albany'),
(4, 2, 'Birmingham'),
(5, 2, 'Montgomery'),
(6, 2, 'Huntsville'),
(7, 3, 'Los Angeles'),
(8, 3, 'San Francisco'),
(9, 3, 'San Diego'),
(10, 4, 'Toronto'),
(11, 4, 'Ottawa'),
(12, 5, 'Vancouver'),
(13, 5, 'Victoria'),
(14, 6, 'Sydney'),
(15, 6, 'Newcastle'),
(16, 7, 'City of Brisbane'),
(17, 7, 'Gold Coast'),
(18, 8, 'Bangalore'),
(19, 8, 'Mangalore'),
(20, 9, 'Hydrabad'),
(21, 9, 'Warangal');

-- --------------------------------------------------------

--
-- Table structure for table `country`
--

CREATE TABLE `country` (
  `country_id` int(11) NOT NULL,
  `country_name` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `country`
--

INSERT INTO `country` (`country_id`, `country_name`) VALUES
(1, 'USA'),
(2, 'Canada'),
(3, 'Australia'),
(4, 'India');

-- --------------------------------------------------------

--
-- Table structure for table `state`
--

CREATE TABLE `state` (
  `state_id` int(11) NOT NULL,
  `country_id` int(11) NOT NULL,
  `state_name` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `state`
--

INSERT INTO `state` (`state_id`, `country_id`, `state_name`) VALUES
(1, 1, 'New York'),
(2, 1, 'Alabama'),
(3, 1, 'California'),
(4, 2, 'Ontario'),
(5, 2, 'British Columbia'),
(6, 3, 'New South Wales'),
(7, 3, 'Queensland'),
(8, 4, 'Karnataka'),
(9, 4, 'Telangana');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `city`
--
ALTER TABLE `city`
  ADD PRIMARY KEY (`city_id`);

--
-- Indexes for table `country`
--
ALTER TABLE `country`
  ADD PRIMARY KEY (`country_id`);

--
-- Indexes for table `state`
--
ALTER TABLE `state`
  ADD PRIMARY KEY (`state_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `city`
--
ALTER TABLE `city`
  MODIFY `city_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22;

--
-- AUTO_INCREMENT for table `country`
--
ALTER TABLE `country`
  MODIFY `country_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;

--
-- AUTO_INCREMENT for table `state`
--
ALTER TABLE `state`
  MODIFY `state_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;





Create Model Class


In Laravel framework, we have to create model class for database related operation. So for create model classe using compost, we have go to command prompt and run following command, this command will make model class file with name Country.php under app/Models folder.


php artisan make:model Country


After create model class, we have to open that file and under that file we have to define mysql table name details and column details.


<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Country extends Model
{
    use HasFactory;

    protected $table = 'country';

    protected $fillable = [
    	'country_name'
    ];
}



Create Controller Class


Under this Laravel framework, for handle HTTP request we have to create controller class. So for create controller using compost, we have go to command prompt and run following command.


php artisan make:controller JointableController


Once your controller class has been create then for open that file, we have go to app/Http/Controllers/JointableController.php file and under this file you have write following code for join multiple table using eloquent model and fetch data from multiple table in single query execution.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Country;

class JointableController extends Controller
{
    function index()
    {
    	$data = Country::join('state', 'state.country_id', '=', 'country.country_id')
              		->join('city', 'city.state_id', '=', 'state.state_id')
              		->get(['country.country_name', 'state.state_name', 'city.city_name']);

       	/*Above code will produce following query

        Select 
        	`country`.`country_name`, 
        	`state`.`state_name`, 
        	`city`.`city_name` 
        from `country` 
        inner join `state` 
        	on `state`.`country_id` = `country`.`country_id` 
        inner join `city` 
        	on `city`.`state_id` = `state`.`state_id`

        */

        return view('join_table', compact('data'));
    }
}

?>


Create View Blade file


For display HTML output in browser, so we have to create view blade file in Laravel framework. In Laravel framework view blade file has been store under resources/views folder. Under this file, we have create join_table.blade.php file. Under this file, it will received data from controller class file. You can find source code of this view blade file in below.


<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>How to Join Table in Laravel 8 using Eloquent Model</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    </head>
    <body>
        <div class="container">    
            <br />
            <h1 class="text-center text-primary">How to Join Multiple Table in Laravel 8 using Eloquent Model</h1>
            <br />
            <div class="table-responsive">
                <table class="table table-bordered table-striped">
                    <thead>
                        <tr>
                            <th>Country</th>
                            <th>State</th>
                            <th>City</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($data as $row)
                            <tr>
                                <td>{{ $row->country_name }}</td>
                                <td>{{ $row->state_name }}</td>
                                <td>{{ $row->city_name }}</td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>
    </body>
</html>


Set Route


Under this Laravel framework, we have to set route of the controller method. For set route in Laravel 8 framework, we have to open routes/web.php file. In Laravel 8 framework for set route, we have to first import our controller class under this web.php file. And for set route you can find source code below.


<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\JointableController;

Route::get('/', function () {
    return view('welcome');
});

Route::get('join_table', [JointableController::class, 'index']);



Run Laravel Server


After follow all above steps now all are set now we want to run Laravel application in browser. So for this, we have to go command prompt and run following command.


php artisan serve


Once you have run above command so after run this command it will provide us base url of our Laravel application. So for check above script output, we have to hit following url in browser.


http://127.0.0.1/join_table


Thursday, 27 August 2020

What to Expect from Laravel 8?


Laravel 8 has got some amazing features for the Laravel Application Development Companies to help them create great apps leveraging such features.

The recent Laracon conclave was organized on Wednesday and it was conducted virtually (online) rather than the usual real-time summer conference in the US. Even though there were a total of 15 speakers, everyone was waiting to listen to that one talented speaker.

The new and unique features in the upcoming release of the framework were announced by Taylor Otwell, the creator of the Laravel framework. Before introducing a plethora of improvements with unique features, Taylor first started with smaller changes. These features have been updated and introduced on September 8th, 2020.

Below are some of the features that were announced:

1. Better Syntax for Event Listeners


While registering a closure-driven event listener you initially have to explain the event class then define the closure and maybe type hint which is the event alert for the closure.


Event::listen(OrderCreated::class, function(OrderCreated $event) { 
	// Do something here
});



You can skip past the first definition of the event class in updated Laravel 8 as the framework will easily interpret it from the type hinted command.


Event::listen(function(OrderCreated $event) { 
    // Do something here
});



2. Improved Landing Page


Now built with TailwindCSS, the page that you will see on clicking the homepage on your first install is a much-improved one. It has a facelift in light or dark shades. This new landing is synced with different Laravel products from different community sites as well as Laravel. If you are looking for some merchandise you can click on the link to the new Laravel shop.

3. Enhanced Route Caching


Assuming that you were already running route cache in your app. With an array of all your routes in it, running the PHP artisan route:cache creates a PHP file that is utilized by Laravel because it’s quicker than parsing your route file(s) on every request. However, until now, your route caching would have failed if there were any closures included in your route or a package entered a route coupled with a closure.

However, Laravel 8 supports the route cache process for routes based on closure. Hence, now you cannot make excuses not to be able to utilize route caching.

4. Maintenance Time: pre-rendered page


Your application will find a lot of errors even if you call for php artisan down command to display your website under maintenance when implementing your application. The auto-load doc is scripted as the dependencies change. It will display an error message before the visitors instead of displaying the maintenance mode window after running the Composer section of the deployment. This was the case in the earlier version of Laravel 7.

This is, however, not an issue in Laravel 8. As part of the artisan down command, your Laravel Development Company can now add the name of a view to a "render" flag.


php artisan down --render="errors::back-soon"


Laravel will preview the errors/back-soon.blade.php view and the site will be put under maintenance mode. The people trying to access the site will be facing a preview. Errors won't be displayed to their screen as the framework won't try to load the composer autoload file.


5. Default app/models directory


Unlike in previous versions of Laravel where a model class was left in the root app directory, Laravel 8 will now utilize an app/models directory. Statistics shown by Taylor show that the app/models directory were being created by developers themselves.

A new model will be created inside the new app/models directory if you utilize any of the commands generated by artisan like PHP artisan make:model. The generator commands will, however, create the model classes in your app directory if you want to store your models in it and delete the new models’ directory.

6. Blade Component Attributes


If a Blade component could be extended (like a component called DangerButton that extends another component known as a button) the $attributes wouldn’t have been passed down by the child button in Laravel 7. However, in Laravel 8, all child components will have attributes passed down to them which will be easier to build extended components.

7. Schema Dump


The Schema Dump feature is one of the most convenient features of Laravel and can be used easily with Laravel Voyager.

Your Laravel development services provider can prune all your existing migrations by first dumping your entire database schema and then by adding the --prune flag.

This will create a single schema dump file and erase all of your old migrations. If you have a lot of migration files this is the perfect way of erasing them all.

You can start after that by adding new migrations again and they will work normally. If you want to clear the migrations folder once you reach a specific number, you can update the schema:dump command again by running it.

8. Unique Access to Maintenance Mode


The only way to keep your website in maintenance mode and at the same time wish to let some select people access it by using the artisan down / artisan up command is by IP white listing. If you have a dynamic IP address or want to let many people access your website it does not work well as the IP is not stable. This is how Laravel 8 handles this issue. While putting your site into maintenance mode, you will now put a "secret" flag.


php artisan down --secret=let-me-in


While your site is in maintenance mode, this secret flag acts as a route. The framework creates a cookie if you can navigate to that and you can browse normally on your website when it redirects you to the landing page of your application.

9. Controllers Namespace Prefix Removed


$namespace was a property in the previous versions of Laravel in the RouteServiceProvider.php. It was used in the namespace of your controllers instantly to prefix them. Laravel may have dual prefixed your namespaces if you were utilizing in your web.php the callable syntax. You can import your controller classes without any issues in your route files as this property has been removed in the latest Laravel update.

Synopsis


Apart from these, there are many other improvements also introduced in Laravel 8. It is great to see Laravel strive hard to bring about improvement in almost every feature. If you plan to use Laravel for your future project, take the help of a Laravel Web Development Company to get the best out of this framework.

Author Bio :


Sanjay is a young entrepreneur who has energy, perfection, focuses, and highly self-motivated and goal-oriented professional with 12+ years of experience in Web Development, Web Services, and Software development with a proven track record in cross-platform execution and excellence in team development & leadership. He has the ability to decipher technology and make it profitable for business solutions. He is a core part of the think tank of World Web Technology Pvt. Ltd.