Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Lelectrolux/f2aa130410b45551b0c3712a2b1e21a4 to your computer and use it in GitHub Desktop.
Save Lelectrolux/f2aa130410b45551b0c3712a2b1e21a4 to your computer and use it in GitHub Desktop.
[Laravel] implicit model binding in controller
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRegionCityHotelTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('regions', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Schema::create('cities', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Schema::create('hotels', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('regions');
Schema::drop('cities');
Schema::drop('hotels');
}
}

Dont forget to do composer dump-autoload after adding the files.

Done for reddit

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class City extends Model
{
public $fillable = ['name'];
public function getRouteKeyName()
{
return 'name';
}
}
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
App\Region::create(['name' => 'texas']);
App\City::create(['name' => 'dallas']);
App\Hotel::create(['name' => 'paradise']);
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Hotel extends Model
{
public $fillable = ['name'];
public function getRouteKeyName()
{
return 'name';
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
class HotelController extends Controller
{
public function show(\App\Region $region, \App\City $city, \App\Hotel $hotel) {
dd($region, $city, $hotel);
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Region extends Model
{
public $fillable = ['name'];
public function getRouteKeyName()
{
return 'name';
}
}
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get('/hotels/{region}/{city}/{hotel}', ['uses' => 'HotelController@show']);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment