Skip to content

Instantly share code, notes, and snippets.

@adamwathan
Created August 11, 2017 20:06
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save adamwathan/ea09266cc4d2b6db784c1da4d79a478b to your computer and use it in GitHub Desktop.
Save adamwathan/ea09266cc4d2b6db784c1da4d79a478b to your computer and use it in GitHub Desktop.
Implementing a RESTful duplicate action
<?php
// ...
Route::post('/proposals/{id}/duplicates', 'ProposalDuplicatesController@store');
<?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;
}
}
<?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,
// ...
]);
}
}
@ninjaparade
Copy link

@adamwathan I do the same thing in my apps as you're showing here. I really like how simple it is.

Thanks for sharing. 🌮

@BadChoice
Copy link

Why not using eloquent's replicate function?

@kfirba
Copy link

kfirba commented Aug 12, 2017

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?

@kamui545
Copy link

Do you use request() in your own apps like that or prefer the dependency injection way? (not trolling, just curious)

@clarkeash
Copy link

@kfirba save returns a boolean

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment