Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.