简体   繁体   中英

Where syntax in Laravel 5 with paginate feature, search feature

On my website, Users can see personal data, search by data or by date and see paginated results.

I'm having trouble to get the paginated data of a user with his "userID" using ->where keyword which need to be integrated in a search feature.

However, I have logic errors and was wondering if someone could help me.


This is my Controller

    public function index()
{
    $q='';
    $from = '';
    $to = '';

    if (Input::get('dateSearchFrom') !='' && Input::get('dateSearchTo') !='') {
        $from = Input::get('dateSearchFrom').' 00:00:00.000';
        $to = Input::get('dateSearchTo').' 23:59:59.999';
    }else if (Input::get('search') !='') {
        $q = Input::get('search');
    }

    if ($q != '') {
        $incomes = Income::latest('created_at')->where('user_id', Auth::user()->id)->orWhere('name','like','%'.$q.'%')->orWhere('money','like','%'.$q.'%')->orWhere('created_at','like','%'.$q.'%')->paginate(4);
    }else if (Input::get('dateSearchFrom') !='' && Input::get('dateSearchTo') !='') {
        $incomes = Income::latest('created_at')->where('user_id', Auth::user()->id)->orWhereBetween('created_at', array($from, $to))->paginate(4);

    }else{
        $incomes = Income::latest('created_at')->where('user_id', Auth::user()->id)->paginate(4);
    }

    $incomes->setPath('income');
    return view('member.income.list')->with([
        'title' => 'Income Data',
        'incomes' => $incomes,
        ]);
}

and this is my model

    use SoftDeletes;

protected $table = 'incomes';

protected $fillable = [
    'id',
    'name',
    'user_id',
    'description',
    'money'
];

Updated

I realised after I posted this that the suggested syntax is also incorrect. You are not giving much in the way of an error so it's hard to solve your problem. I cannot find Model::latest() but I assumed that you already had that covered.

It looks as if you're trying to paginate results ordering by created_at in descending order. If so, this would be the correct syntax:

$incomes = Income::where('user_id', Auth::user()->id)->orderBy('created_at', 'desc')->paginate(4);

I wrongly thought that ->get() is all that was necessary as I believed it worked on my copy but I ran into an error.

Original

Have you tried using ->get() ? Like this:

$incomes = Income::latest('created_at')->where('user_id', Auth::user()->id)->get()->paginate(4);`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM