Laravel检查用户的记录

i have this controller created. This is where i get all the ads (avisos) created from the users.

class AdController extends Controller
  {
  public function index(Request $request)
  {

    $page = $request->get('page',1);
    $perPage = 15;
    $offset = ($page * $perPage) - $perPage;


    $avisos = Ad::select(['id','user_id','title','content','created_at','moderated_at'])
            ->WithNotModerate()
            ->orderBy('moderated_at', 'asc')
            ->paginate(15);



    if($request->has('user_id'))
    $avisos = Ad::select(['id','user_id','title','content','created_at','moderated_at'])
                ->WithNotModerate()
                ->where('user_id','like','%'.$request->user_id.'%')
                ->orderBy('moderated_at', 'asc')
                ->paginate(15);

    if ($request->ajax()) {
        return view('admin.avisos.data', ['avisos' => $avisos])->render();  
    }

    return view('admin.avisos.index', compact('avisos'));
}

And here is where they are all rendered in my blade view, all ads from all users.

@foreach ($avisos as $aviso)
    <tr>
    <td>{{$aviso->id}}</td>
    <td>{{$aviso->user_id}}</td>
    <td>{{str_limit($aviso->title, 40)}}</div></td>
    <td>{{str_limit($aviso->content, 40)}}</div></td>
    <td>{{$aviso->created_at->diffForHumans()}}</td>
    <td>{{$aviso->moderated_at}}</td>
    </tr>
@endforeach

I want to check if the user has more than one ad 'created_at' in the past 15 days so i can add a class to the table row

I tried something like this

  @foreach ($avisos as $aviso)
    <?php
    $date = \Carbon\Carbon::today()->subDays(15);
    $already = DB::table('ads')
          ->where('user_id','=','$aviso->user_id')
          ->where('created_at' ,'=', date($date))
          ->get();
    var_dump($already); 
    ?>
    <tr>
    <td>{{$aviso->id}}</td>
    <td>{{$aviso->user_id}}</td>
    <td>{{str_limit($aviso->title, 40)}}</div></td>
    <td>{{str_limit($aviso->content, 40)}}</div></td>
    <td>{{$aviso->created_at->diffForHumans()}}</td>
    <td>{{$aviso->moderated_at}}</td>
    </tr>
  @endforeach

Returns

object(Illuminate\Database\Eloquent\Collection)#3073 (1) { ["items":protected]=> array(0) { } } for each ad...

You are using the date function incorrectly. First argument of date excepts a valid format in form of a string, what your giving is a Carbon instance.

But because you already have an instance of Carbon, you don't need to use date. Format the Carbon instance instead to match what you have in the database.

You are also checking user_id against the string $aviso->user_id instead of the actual variable value.

There is a difference between '$aviso->user_id' and $aviso->user_id. Remove the single quotes to get the expected value.

$date = \Carbon\Carbon::today()->subDays(15);
$already = DB::table('ads')
      ->where('user_id','=',$aviso->user_id)
      ->where('created_at' ,'=', $date->format('Y-m-d H:i:s'))
      ->get();