-
-
Save adamwathan/ea09266cc4d2b6db784c1da4d79a478b to your computer and use it in GitHub Desktop.
Implementing a RESTful duplicate action
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 | |
// ... | |
Route::post('/proposals/{id}/duplicates', 'ProposalDuplicatesController@store'); | |
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 App\Http\Controllers; | |
use Illuminate\Http\Request; | |
class ProposalDuplicatesController extends Controller | |
{ | |
public function store($id) | |
{ | |
$proposal = Proposal::findOrFail($id); | |
request()->validate([ | |
'new_title' => 'required', | |
]); | |
$duplicate = tap($proposal->duplicateAs(request('new_title')))->save(); | |
return $duplicate; | |
} | |
} |
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 App; | |
use Illuminate\Database\Eloquent\Model; | |
class Proposal extends Model | |
{ | |
public function duplicateAs($newTitle) | |
{ | |
return new Proposal([ | |
'title' => $newTitle, | |
'user_id' => $this->user_id, | |
'summary' => $this->summary, | |
// ... | |
]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Do you use
request()
in your own apps like that or prefer the dependency injection way? (not trolling, just curious)