Laravel: Joining Tables

Submitted by: 
Language: 
Visitors have accessed this post 682 times.

Getting Started

Note: I'm using hosted bootstrap so you need internet connection for them to work.

First, we're going to create a new project and I'm gonna name it site and add it to localhost with the name site.dev. If you have no idea on how to do this, please refer to my tutorial Installing Laravel - PHP Framework.

Setting up our Database

1. Open your phpMyAdmin and create a new database. In my case, I've created a database named join.

2. In our project, open .env file and update the ff lines depending on your setting.

  1. DB_DATABASE=join
  2. DB_USERNAME=root
  3. DB_PASSWORD=

Creating our Controller

1. In command prompt, navigate to your project and type:

php artisan make:controller EmployeeController

This will create our controller in the form of EmployeeController.php located in app/Http/Controllers folder.

2. Open EmployeeController.php and edit it with the ff codes:

  1. <?php
  2.  
  3. namespace App\Http\Controllers;
  4.  
  5. use Illuminate\Http\Request;
  6. use DB;
  7. use App\Employee;
  8.  
  9. class EmployeeController extends Controller
  10. {
  11. public function index(){
  12. $employee = DB::table('employees')
  13. ->join('genders', 'genders.id', '=', 'employees.gender_id')
  14. ->join('positions', 'positions.id', '=', 'employees.position_id')
  15. ->get();
  16.  
  17. $gender = DB::table('genders')
  18. ->get();
  19.  
  20. $position = DB::table('positions')
  21. ->get();
  22.  
  23. return view('home', ['employees' => $employee , 'genders' => $gender , 'positions' => $position]);
  24. }
  25.  
  26. public function save(Request $request){
  27. $employee = new Employee;
  28. $employee->firstname = $request->input('firstname');
  29. $employee->lastname = $request->input('lastname');
  30. $employee->gender_id = $request->input('gender');
  31. $employee->position_id = $request->input('position');
  32.  
  33. $employee->save();
  34.  
  35. return redirect('/');
  36. }
  37. }

Creating our Models

1. In command prompt, navigate to our project and type:

For Employee:
php artisan make:model Employee -m

For Position:
php artisan make:model Position -m

For Gender:
php artisan make:model Gender -m

This will create our models Member.php, Position.php and Gender.php located in app folder. It will also create the migrations for us due to the -m that we added in creating the model located in database/migrations folder.

Edit this migrations with the ff to set up our table:

create_employees_table.php

  1. <?php
  2.  
  3. use Illuminate\Support\Facades\Schema;
  4. use Illuminate\Database\Schema\Blueprint;
  5. use Illuminate\Database\Migrations\Migration;
  6.  
  7. class CreateEmployeesTable extends Migration
  8. {
  9. /**
  10.   * Run the migrations.
  11.   *
  12.   * @return void
  13.   */
  14. public function up()
  15. {
  16. Schema::create('employees', function (Blueprint $table) {
  17. $table->increments('id');
  18. $table->string('firstname');
  19. $table->string('lastname');
  20. $table->integer('gender_id');
  21. $table->integer('position_id');
  22. $table->timestamps();
  23. });
  24. }
  25.  
  26. /**
  27.   * Reverse the migrations.
  28.   *
  29.   * @return void
  30.   */
  31. public function down()
  32. {
  33. Schema::dropIfExists('employees');
  34. }
  35. }

create_genders_table.php

  1. <?php
  2.  
  3. use Illuminate\Support\Facades\Schema;
  4. use Illuminate\Database\Schema\Blueprint;
  5. use Illuminate\Database\Migrations\Migration;
  6.  
  7. class CreateGendersTable extends Migration
  8. {
  9. /**
  10.   * Run the migrations.
  11.   *
  12.   * @return void
  13.   */
  14. public function up()
  15. {
  16. Schema::create('genders', function (Blueprint $table) {
  17. $table->increments('id');
  18. $table->string('gender');
  19. $table->timestamps();
  20. });
  21. }
  22.  
  23. /**
  24.   * Reverse the migrations.
  25.   *
  26.   * @return void
  27.   */
  28. public function down()
  29. {
  30. Schema::dropIfExists('genders');
  31. }
  32. }

create_positions_table.php

  1. <?php
  2.  
  3. use Illuminate\Support\Facades\Schema;
  4. use Illuminate\Database\Schema\Blueprint;
  5. use Illuminate\Database\Migrations\Migration;
  6.  
  7. class CreatePositionsTable extends Migration
  8. {
  9. /**
  10.   * Run the migrations.
  11.   *
  12.   * @return void
  13.   */
  14. public function up()
  15. {
  16. Schema::create('positions', function (Blueprint $table) {
  17. $table->increments('id');
  18. $table->string('title');
  19. $table->timestamps();
  20. });
  21. }
  22.  
  23. /**
  24.   * Reverse the migrations.
  25.   *
  26.   * @return void
  27.   */
  28. public function down()
  29. {
  30. Schema::dropIfExists('positions');
  31. }
  32. }

Migrating

In command prompt, navigate to your project and type: php artisan migrate

It will then create our database migration.

If you have an error like this:

[Illuminate\Database\QueryException]
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was t
oo long; max key length is 767 bytes (SQL: alter table `users` add unique `
users_email_unique`(`email`))

You can solve this by opening AppServiceProvider.php located in app/Providers folder.

Add this line: use Illuminate\Support\Facades\Schema;

In boot add this line: Schema::defaultStringLength(191);

migration error

Run php artisan migrate again and make sure that your database is empty because it will have another error if its not.

Creating our Routes

In routes folder, open web.php and edit it with the ff codes:

  1. <?php
  2.  
  3. Route::get('/', '<a href="mailto:[email protected]" rel="nofollow">[email protected]</a>');
  4.  
  5. Route::post('/save', '<a href="mailto:[email protected]" rel="nofollow">[email protected]</a>');

Creating our Views

In resources/views folder, create the ff files:

home.blade.php

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Laravel: Join Table</title>
  6. <link rel="stylesheet" href="<a href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"" rel="nofollow">https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"</a> />
  7. <link rel="stylesheet" href="/css/app.css">
  8. <script src="<a href="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  9. " rel="nofollow">https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></scri...</a> <script src="<a href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  10. " rel="nofollow">https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></s...</a> <link href="<a href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"" rel="nofollow">https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min....</a> rel="stylesheet">
  11. </head>
  12. <body>
  13. <div class="container">
  14. <h1 class="page-header text-center">Laravel: Join Table</h1>
  15. <div class="row">
  16. <div class="col-md-10 col-md-offset-1">
  17. <h2>Employee Table
  18. <a href="#addnew" data-toggle="modal" class="btn btn-primary pull-right"><span class="glyphicon glyphicon-plus"></span> Employee</a>
  19. </h2>
  20. <table class="table table-bordered table-striped">
  21. <thead>
  22. <th>Firsttname</th>
  23. <th>Lastname</th>
  24. <th>Gender</th>
  25. <th>Position</th>
  26. </thead>
  27. <tbody>
  28. @foreach($employees as $employee)
  29. <tr>
  30. <td>{{$employee->firstname}}</td>
  31. <td>{{$employee->lastname}}</td>
  32. <td>{{$employee->gender}}</td>
  33. <td>{{$employee->title}}</td>
  34. </tr>
  35. @endforeach
  36. </tbody>
  37. </table>
  38. </div>
  39. </div>
  40. </div>
  41. @include('modal')
  42. </body>
  43. </html>

modal.blade.php

  1. <!-- Add Modal -->
  2. <div class="modal fade" id="addnew" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  3. <div class="modal-dialog" role="document">
  4. <div class="modal-content">
  5. <div class="modal-header">
  6. <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
  7. <h4 class="modal-title text-center" id="myModalLabel">Add New Employee</h4>
  8. </div>
  9. <div class="modal-body">
  10. <form action="{{ URL::to('save') }}" method="POST">
  11. {{ csrf_field() }}
  12. <div class="form-group">
  13. <div class="row">
  14. <div class="col-md-2" style="margin-top:7px;">
  15. <label for="firstname">Firstname</label>
  16. </div>
  17. <div class="col-md-10">
  18. <input type="text" name="firstname" class="form-control" placeholder="Input Firstname" required>
  19. </div>
  20. </div>
  21. </div>
  22. <div class="form-group">
  23. <div class="row">
  24. <div class="col-md-2" style="margin-top:7px;">
  25. <label for="lastname">Lastname</label>
  26. </div>
  27. <div class="col-md-10">
  28. <input type="text" name="lastname" class="form-control" placeholder="Input Lastname" required>
  29. </div>
  30. </div>
  31. </div>
  32. <div class="form-group">
  33. <div class="row">
  34. <div class="col-md-2" style="margin-top:7px;">
  35. <label for="lastname">Gender</label>
  36. </div>
  37. <div class="col-md-10">
  38. <select class="form-control" name="gender">
  39. @foreach($genders as $gender)
  40. <option value="{{ $gender->id }}">{{ $gender->gender }}</option>
  41. @endforeach
  42. </select>
  43. </div>
  44. </div>
  45. </div>
  46. <div class="form-group">
  47. <div class="row">
  48. <div class="col-md-2" style="margin-top:7px;">
  49. <label for="lastname">Position</label>
  50. </div>
  51. <div class="col-md-10">
  52. <select class="form-control" name="position">
  53. @foreach($positions as $position)
  54. <option value="{{ $position->id }}">{{ $position->title }}</option>
  55. @endforeach
  56. </select>
  57. </div>
  58. </div>
  59. </div>
  60. </div>
  61. <div class="modal-footer">
  62. <button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-times"></i> Cancel</button>
  63. <button type="submit" class="btn btn-primary"><i class="fa fa-save"></i> Save</button>
  64. </form>
  65. </div>
  66. </div>
  67. </div>
  68. </div>

Running our Server

In your web browser, type the name that you added in localhost for your project in my case, site.dev.

That ends this tutorial. Happy Coding :)


Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.