e4rthdog
e4rthdog

Reputation: 5223

Simplify store controller method on laravel 5

This is my store method to save a post.

public function store(CreatePostRequest $request)
{
    $post = new Post([
        'title' => $request['title'],
        'content' => Crypt::encrypt($request['content']),
        'published_at' => Carbon::now()
    ]);
    $post->user()->associate(Auth::user());
    $newPost=Post::create($post->toArray());
    $this->syncTags($newPost, $request['tag_list']);
    return redirect('posts')->withMessage('Post Saved Successfully !!!');
}

In laracasts tutorial he is just doing a

Article::create($request->all());

I need to do the extra stuff like encrypt, but am i cluttering the method? could it be cleaner?

Upvotes: 0

Views: 1082

Answers (1)

dotty
dotty

Reputation: 41433

Do it in the Model. I use the set/get*Attribute() method to change stuff on the fly.

So you could use Article::create($request->all()); then in the model use the fillable array to only autofill what is allowed (such as title, content and published_at).

then use something like (in the model)

function setContentAttribute( $value ){
    $this->attributes['content'] = Crypt::encrypt($value);
}

In fact you could also adapt this approach so that the published_at attribute is set to today, or even better use your database to provide now()s time.

Upvotes: 3

Related Questions