jeudi 24 mars 2016

Laravel - Always Returning Results From Database Model Even When Nonexistent

I am trying to determine the relationship between two databases to determine if a user has "liked" a post.

This entails the following vectors:

First the user loads up the collection of posts, or "wall"

This is that route:

Route::get('/wall',[
    'uses' => 'punscontroller@wall',
    'as'   => 'puns.wall'
]);

The relevant controller:

 public function wall()
           {
 if (Auth::check() && Auth::user()->AccountSetup != "FALSE")
{
$data = array();
$wall = Wall::orderBy('id', 'desc')->take(20)->get();
foreach ($wall as $snail){
    $type = $snail["post_type"];
    $id = json_decode($snail["assetID"])->id;
    if(count(Like::where('assetType', $type)->where('user_id', Auth::user()->id)->where('assetId', $id)) > 0){
        //you already liked this assetID
        //push into data
        $datatherobot = array(
    'wall'  => $snail,
    'liked?' => "y"
);
    }
    else{
    $datatherobot = array(
    'wall'  => $snail,
    'liked?' => "n"

);  
    }
array_push($data,$datatherobot);    
}
return view('wall')->with('data', $data);   ;
}
else{
echo "Insufficient Privileges! Please visit the homepage and login!";
}
       }

The view then looks something like this:

@foreach ($data as $snail)
<div class="wallfunctions">
          @if ($snail["liked?"] == "y") <i class="fa fa-thumbs-up liked" style="font-size: 100%;"></i> @else<i class="fa fa-thumbs-up" style=""></i>@endif<i class="fa fa-comments" style="color:black;padding:0 5%"></i>
          </div>
@endforeach

My problem is for each post on the wall, I am getting every single post liked when only the first post should be liked for the logged in user (I only liked one post on the wall, not all of them).

I don't understand why this is happening because if I follow my controller logic while looking at my datatables, I don't see how the count is always greater than 0 regardless of which wall post it is looking at.

Is there some mistake in my code?

Take a look at the two tables in question yourself and see that there should only be one liked post for the logged in user (user_id == 2).

Wall Data Table

Likes Data Table



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire