-
-
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, | |
// ... | |
]); | |
} | |
} |
Why not using eloquent's replicate function?
Why do you need the tap
call here? The duplicateAs
method returns a new Proposal object and you just call save
on it. What am I not seeing?
Do you use request()
in your own apps like that or prefer the dependency injection way? (not trolling, just curious)
@kfirba save
returns a boolean
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@adamwathan I do the same thing in my apps as you're showing here. I really like how simple it is.
Thanks for sharing. 🌮