input('search'); $clients = Client::query() ->when($query, function ($q) use ($query) { // Si hay búsqueda, filtra por nombre o SKU return $q->where('name', 'like', "%{$query}%"); }) ->orderBy('name', 'asc') //->orderBy('create_at', 'asc') ->paginate(10) // Paginamos de a 10 ->withQueryString(); // Mantiene el filtro de búsqueda al cambiar de página return view('clients.index', compact('clients')); } /** * Show the form for creating a new resource. */ public function create() { return view('clients.create'); } /** * Store a newly created resource in storage. */ public function store(Request $request) { $validated = $request->validate([ 'name' => 'required|string|max:255', 'phone' => 'nullable|string|max:50', 'email' => 'nullable|email|max:255|unique:clients,email', 'address' => 'nullable|string|max:255', ]); // 1. Guardamos el cliente en una variable para tener su ID $client = Client::create($validated); // 2. Verificamos el origen if ($request->input('origin') === 'sales') { // Si vino de ventas, volvemos a ventas // Y pasamos el ID del nuevo cliente para auto-seleccionarlo return redirect()->route('sales.create', ['new_client_id' => $client->id]) ->with('success', 'Cliente creado. Ya puedes seleccionarlo.'); } // 3. Si no, comportamiento normal (volver al index de clientes) return redirect()->route('clients.index') ->with('success', 'Cliente creado correctamente.'); } /** * Display the specified resource. */ public function show(string $id) { // } public function edit(Client $client) { // Reutilizamos la vista de create, o creamos una edit.blade.php similar return view('clients.edit', compact('client')); } public function update(Request $request, Client $client) { $validated = $request->validate([ 'name' => 'required|string|max:255', 'phone' => 'nullable|string|max:50', 'email' => 'nullable|email|max:255|unique:clients,email,' . $client->id, // Ignorar email propio 'address' => 'nullable|string|max:255', ]); $client->update($validated); return redirect()->route('clients.index')->with('success', 'Cliente actualizado correctamente.'); } /** * Remove the specified resource from storage. */ public function destroy(Client $client) { try { $client->delete(); return redirect()->route('clients.index')->with('success', 'Cliente eliminado correctamente.'); } catch (\Illuminate\Database\QueryException $e) { return back()->with('error', 'No se puede eliminar el cliente porque tiene ventas registradas.'); } } }