You could wrap the entire thing in a DB transaction and then, if validation fails at any point, rollback the transaction and then delete the created post.
Aug 11, 2014
4
Level 2
created() boot method trigger with validation?
I had it creating() to begin with, but these are associated tables and I need to attach the ID that is inserted after the post is created.. so, this is my code:
public static function boot()
{
parent::boot();
Post::created(function($post)
{
// Upload media
if( Input::get('gallery_exist') == 1 )
{
foreach( Input::file('gallery') as $image )
{
$uploader = new Uploader();
$uploader->setDirectory( static::$directory );
if( ! $uploader->uploadImage( $image, array(static::$thumbnailWidth, static::$thumbnailHeight) ) )
{
$post->errors()->add('upload', 'Image upload failed.');
// Remove post
$post->delete();
return false;
}
$file = $uploader->getRecentFile();
// Insert image
$media = new PostMedia();
$media->project_post_id = $post->id;
$media->url = $file;
$media->type = 1;
if( ! $media->save() )
{
$post->errors()->add('gallery', $media->errors()->first() );
// Remove post
$post->delete();
return false;
}
}
}
if( Input::get('youtube_exist') == 1 )
{
foreach( Input::get('videos') as $video )
{
$media = new PostMedia();
$media->project_post_id = $post->id;
$media->url = $video;
$media->type = 2;
if( ! $media->save() )
{
$post->errors()->add('video', $media->errors()->first() );
// Remove post
$post->delete();
return false;
}
}
}
// Upload product line attachments
if(count( Input::get('product_line_id') ) > 0)
{
foreach( Input::get('product_line_id') as $product )
{
$line = new PostProduct();
$line->project_post_id = $post->id;
$line->product_line_id = $product;
if( ! $line->save() )
{
$post->errors()->add('product', $line->errors()->first() );
$post->delete();
return false;
}
}
}
return true;
});
}
I'm passing $post->id in multiple places so the post model needs to save so created() works fine. But then if some of their image attachments fail, then I want to remove the post and return the user back to the screen with errors.. what's the best way of going about this? It doesn't seem like this is what I want since it ignores all validation rules for these scenarios and still publishes the post anyway and says everything was okay since it doesn't care about the return value like creating() does..
Please or to participate in this conversation.