mardi 28 novembre 2017

output only updated after second form submit

I have a from with an input that filters a database query by a string. Often, but strangely enough not always, I have to send this form twice to get updated data after changing the filter string. The filter string is updated upon sending the form in because I flash the request. So that part works.

In between sending the forms there is also an ajax call to the same route (json return). Maybe that is mixing something up with the csrf tokens?

Why is the data not updated? It seems it is cached? I followed the basic tutorial. (I know the code is not perfect, it's my first laravel project)

Here is the route: (I change the real name of the model to "Model")

Route::get('myRoute', ['as' => 'myRoute', function (\Illuminate\Http\Request $request) {
    $request->flash();
    $model = new \App\Model();

    if($request->accepts('text/html')) {
        if($request->has('filter')) {
            $searchString = $request->filter;
        } else {
            $searchString = '';
        }
        return view('myView', [
            'searchString' => $searchString,
            'models' => $model->getModels()
        ]);
    } elseif($request->accepts('application/json')) {
        return response()->json($model->getModels());
    }
}]);

And here the relevant part of the Model:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Model extends Model
{
    public function getRequests()
    {

        if (request()->has('filter')) {
            return $this->searchByFilter();
        }

        if (request()->has('email')) {
            return $this->searchByEmail();
        }
    }

    private function searchByFilter()
    {
        $filter = request();
        if (is_null($filter)) {
            return $this->orderBy('created', 'asc')->get();
        }
        return $this->selectRaw(
            "*, MATCH(
                    something
                ) AGAINST ('{$filter}' IN NATURAL LANGUAGE MODE) as relevance")
            ->whereRaw("MATCH(
                            something
                        ) AGAINST ('{$filter}' IN NATURAL LANGUAGE MODE)")
            ->orderBy('relevance', 'desc')
            ->limit(25)
            ->get();
    }
}

The view is very simple:

@if (!is_null($models))
    @forelse ($models as $key => $model)
        <div></div
    @empty
        <p>no results.</p>
    @endforelse
@else
    <p>please filter something.</p>
@endif



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire