Laravel5:原生PHP会话代码转Laravel会话代码求助
Converting Raw PHP Session Basket Logic to Laravel
Got it, let's get your shopping basket session logic converted to Laravel's system properly. First, I'll note a small inconsistency in your original code (you check $_GET['amount'] but loop using $_POST['amount'])—I'll fix that in the Laravel version to use a single source for the amount value.
Here's how to replicate your exact behavior in Laravel, using its built-in session helpers and request handling:
Controller Example
If you're using a controller method (the recommended approach in Laravel), you can do this:
use Illuminate\Http\Request; class BasketController extends Controller { public function update(Request $request) { $status = trim($request->query('status')); switch ($status) { case '': break; case 'basket': // Get the item code from the GET parameters $itemCode = $request->query('item_code'); // Get the amount from either GET or POST (fixes the original inconsistency) // Default to 1 if no amount is provided $amount = (int) $request->input('amount', 1); // Add the item to the basket session the specified number of times for ($i = 1; $i <= $amount; $i++) { session()->push('basket', $itemCode); } break; } // Redirect back or return a response as needed return redirect()->back()->with('success', 'Item added to basket!'); } }
Route Closure Example
If you prefer a quick route closure for testing:
use Illuminate\Http\Request; Route::get('/basket/update', function (Request $request) { $status = trim($request->query('status')); if ($status === 'basket') { $itemCode = $request->query('item_code'); $amount = (int) $request->input('amount', 1); // A cleaner alternative to the for loop foreach (range(1, $amount) as $_) { session()->push('basket', $itemCode); } } return response()->json([ 'basket' => session('basket'), 'message' => 'Basket updated' ]); });
Key Notes:
session()->push('basket', $itemCode)is Laravel's equivalent of$_SESSION['basket'][] = $itemCode—it appends items to the session array.$request->query('key')specifically gets GET parameters, while$request->input('key')works for both GET and POST, which fixes the mixed$_GET/$_POSTissue in your original code.- To view the basket contents at any time, use
session('basket')(e.g.,dd(session('basket'))for debugging).
内容的提问来源于stack exchange,提问作者Mingeun Kim
相关产品推荐
相关产品推荐

