Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@desjob
Created October 21, 2015 15:45
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save desjob/485f03b22341748926ac to your computer and use it in GitHub Desktop.
Save desjob/485f03b22341748926ac to your computer and use it in GitHub Desktop.
binding models on request data in laravel
<?php namespace LS\Http\Controllers;
...
class AnnualReportController extends Controller
{
public function store(BookRequest $request, Book $newBook, Author $byAuthor)
{
$newBook->fill($request->all());
$newBook->author()->associate($byAuthor);
$newBook->save();
return redirect('/book')->with('success', 'book has been succesfully created');
}
<?php
namespace LS\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Input;
class RequestServiceProvider extends ServiceProvider
{
public function register()
{
/**
* In this example, when the POST data contains author_id,
* the correct author model will be available from the service container.
* This will work similar to route model binding.
*/
$this->model('author_id', \Author::class);
}
/**
* Bind models based on a key in the request data
*
* @param string $key
* @param string $className
*/
private function model($key, $className)
{
if (Input::has($key)) {
$this->app->bind($className, function () use ($key, $className) {
return $className::findOrFail(Input::get($key));
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment