I'm new to Laravel. I have searched this site but can't find specific help. I'm trying to pass a value of a variable(which is $Like) from Controller to the blade view, but the browser gives an error of
Undefined variable: Like
Here is the part of my view code (dashboard.blade.php):
@foreach($posts as $post)
<article class="post" data-postid="{{ $post->id }}">
<div class="interaction">
<a href="#" class="like">{{$Like }}</a> |
</div>
</article>
@endforeach
<script>
var token = '{{ Session:: token() }}';
var urlLike = '{{ route('like') }}';
</script>
part of my controller(PostController.php) code:
public function LikePost(Request $request) // post type
{
$post_id = $request['postId']; // postId from script.js
$is_Like = $request['isLike'] === 'true'; // from script.js ...
$update = false;
$post = Post::find($post_id);
$user = Auth::user();
$like = $user->likes()->where('post_id', $post_id)->first();
$like->like = $is_Like;
$like->user_id = $user->id;
$like->post_id = $post->id;
$Like = $like ? $like->like == 1 ? 'You like this' : 'Like' : 'Like';
return redirect()->route('dashboard')->with('Like', $Like);
}
here is the part of my route code:
//for like post
Route::post('/like', [
'uses'=> 'PostController@LikePost',
'as'=> 'like'
]);
here is my script.js:
$('.like').on('click', function (event) {
event.preventDefault();
postId = event.target.parentNode.parentNode.dataset['postid'];
// check whether previous element of like/dislike is null or not
var isLike = event.target.previousElementSibling == null;
$.ajax({
method: 'POST',
url: urlLike,
data: {
isLike: isLike,
postId: postId,
_token: token
}
}).done(function () {
event.target.innerText = isLike ? event.target.innerText == 'Like' ? 'You like this' : 'Like' : event.target.innerText == 'Dislike' ? 'You dislike this' : 'Dislike';
if (isLike) {
event.target.nextElementSibling.innerText = 'Dislike';
} else {
event.target.previousElementSibling.innerText = 'Like';
}
});
});
I tried in many ways. but every time it shows me an error,
undefined variable: Like in dashboard.blade.php
Anyone help please.....
$Like = $like ? $like->like == 1 ? 'You like this' : 'Like' : 'Like';Chaining ternary statements is a very bad practice.