andrewelkins / Laravel-4-Bootstrap-Starter-Site

Laravel 4 Starter Site is a basic blog application using several nice community packages.
1.77k stars 602 forks source link

[Request] Use view composers to bind commenting form. #236

Open Aristona opened 11 years ago

Aristona commented 11 years ago

Hi,

I just downloaded the starter kid and came across this:

@if ( ! Auth::check())
You need to be logged in to add comments.<br /><br />
Click <a href="{{{ URL::to('user/login') }}}">here</a> to login into your account.
@elseif ( ! $canComment )
You don't have the correct permissions to add comments.
@else

@if($errors->has())
<div class="alert alert-danger alert-block">
<ul>
@foreach ($errors->all() as $error)
    <li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif

<h4>Add a Comment</h4>
<form  method="post" action="{{{ URL::to($post->slug) }}}">
    <input type="hidden" name="_token" value="{{{ Session::getToken() }}}" />

    <textarea class="col-md-12 input-block-level" rows="4" name="comment" id="comment">{{{ Request::old('comment') }}}</textarea>

    <div class="form-group">
        <div class="col-md-12">
            <input type="submit" class="btn btn-default" id="submit" value="Submit" />
        </div>
    </div>
</form>
@endif
@stop

Excuse me - but this is crazy. Incredible amount of unnecessary work in our views, which is also unmaintainable.

Correct way should be:

View::composer(array('site.view_post'), function($view) 
{

      if( ! Auth::check()) 
         return $view->nest('commentForm', 'site.partials.login');

     // Handle $canComment here, preferably render error partial

     // Finally
     return $view->nest('commentForm', 'site.partials.commentForm', array('postID' => $postID, 'identifier' => $identifier))

});

Now, you can bind the comment form whereever you want only by adding view name into the composer array.

What benefits do you get?

  1. You can maintain it from a single place.
  2. Incredibly easily to support adding commenting form on other views.
  3. Take out the unnecessary logic from your views.
  4. Take out unnecessary ->with() calls on your controllers. 5, Generally, a better practice use.
andrewelkins commented 10 years ago

Agreed. I'll add this in.

gcphost commented 10 years ago
View::composer(array('*view_post'), function($view) 
{
    $viewdata=$view->getData();
    if(!Auth::check()) return $view->nest('commentForm', 'site/blog/comment_auth');
    if(!$viewdata['canComment']) return $view->nest('commentForm', 'site/blog/comment_perm');
    return $view->nest('commentForm', 'site/blog/comment_form', array('post' => $viewdata['post']));

});

Then split out the html to seperate files, comment_auth, _perm and _form and replace them with {{ $commentForm }} in view_post