lundi 2 juillet 2018

Laravel + add element to cookie and do not include in query

I'm trying to do the following:

At page load:

Select one random idea from database.

My code:

public function index()
{
    if(Cookie::get('ideas'))
    {
        $ideas = Cookie::get('ideas');
        $ideas = unserialize($ideas);
    }
    else
    {
        $ideas = array();
    }

    $random_idea = Idea::inRandomOrder()->first();
    $ideas[] = $random_idea->id;

    Cookie::queue('ideas', serialize($ideas));

    return view('app', compact('random_idea'));
}

I'm checking if the cookie is already set, if set, add the random idea to the cookie. If not, create new array and add the id to the array.

When they click a button on page (through ajax call).

My code:

public function idea(Request $request)
{
    $ideas = Cookie::get('ideas');
    $ideas = unserialize($ideas);

    $random_idea = Idea::inRandomOrder()->first();
    $ideas[] = $random_idea->id;

    Cookie::queue('ideas', serialize($ideas));

    return response()->json($random_idea);
}

I have 2 problems:

  • The cookie variable is an array with always one element (id isn't added to the array)
  • How can I select one random element from database that's NOT in the array?


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire