Created
October 21, 2015 15:45
-
-
Save desjob/485f03b22341748926ac to your computer and use it in GitHub Desktop.
binding models on request data in laravel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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'); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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