4 months ago

Output from model controller to html

Posted 4 months ago by abarua

Hi, can someone please tell me how to output from controller to html form. I want to change the label of an anchor from "Like" to "Liked" if the user has already clicked the link previously. Thanks in advance!

Here is the html:

<section class="row posts">
        <div class="col-md-6 col-md-3-offset">
            <header><h3>other posts</h3></header>
            @foreach($posts as $post)
            <article class="post">
                <p>{{ $post->content }}</p>
                <div class="info">Posted by {{ $post->user->username }} on {{ $post->created_at }}</div>
                <div class="interaction">
                    <a href="#" class="like" data-postid="{{ $post->id }}">Like</a>
                    @if(Auth::user() == $post->user)
                        <a href="#" class="edit" data-postid="{{ $post->id }}">Edit</a> |
                        <a href="{{ route('post.delete',['post_id' => $post->id]) }}">Delete</a>
        var token = '{{ Session::token() }}';
        var urlLike = '{{ route('like') }}';

The javascript to get postid from the form:

$('.like').on('click', function (event) {
        postId = event.target.dataset.postid;
        var isLike = event.target.previousElementSibling==null ? true:false;
           method: 'POST',
           url: urlLike,
           data: {isLike: isLike, postId: postId, _token: token}
        .done(function () {
            //change the page

The route:

        'uses' => '[email protected]',
        'as' => 'like'

Finally, can someone please tell me how to send the output from the controller to the html form:

public function postLikePost(Request $request)
        $post_id = $request['postId'];
        $is_like = $request['isLike'] === 'true' ? true : false;
        $post = Post::find($post_id);
        if (!$post)
            return null;
        $user = Auth::user();
        $like = $user->likes()->where('post_id',$post_id)->first();
    //user already liked the post
            //output to "Like" in the html form here
            return null;
            $like = new Like();
            $like->post_id = $post->id;
            $like->user_id = $user->id;
            //output to "Liked" in the html from here
        return null;

Please sign in or create an account to participate in this conversation.