osb/app/Http/Controllers/UserController.php

84 lines
1.9 KiB
PHP

<?php
namespace App\Http\Controllers;
use Carbon\Carbon;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;
use Illuminate\Validation\Rule;
use App\Http\Requests\UserEdit;
use App\Models\{Supplier,User};
class UserController extends Controller
{
/**
* Update user settings
*
* @param UserEdit $request
* @param User $o
* @return RedirectResponse
*/
public function edit(UserEdit $request,User $o): RedirectResponse
{
foreach (Arr::except($request->validated(),['password']) as $field => $value)
$o->{$field} = $value;
if ($x=$request->validated('password'))
$o->password = Hash::make($x);
return redirect()
->back()
->with('success',($o->isDirty() && $o->save()) ? 'User Updated' : 'No Changes');
}
/**
* Add a supplier to a user's profile
*
* @param Request $request
* @param User $o
* @return \Illuminate\Http\RedirectResponse
*/
public function supplier_addedit(Request $request,User $o)
{
Session::put('supplier_update',true);
$validated = $request->validate([
'id'=> ['required','string',Rule::unique('supplier_user')->where(fn ($query) => $query->where('supplier_id',$request->supplier_id)->where('user_id','<>',$o->id))],
'supplier_id'=>'required|exists:suppliers,id',
]);
$o->suppliers()->attach([
$validated['supplier_id'] => [
'id'=>$validated['id'],
'site_id'=>$o->site_id,
'created_at'=>Carbon::now(),
]
]);
return redirect()
->back()
->with('success','Supplier Added');
}
/**
* Remove a supplier from a user's profile
*
* @param User $o
* @param Supplier $so
* @return \Illuminate\Http\RedirectResponse
*/
public function supplier_delete(User $o,Supplier $so)
{
Session::put('supplier_update',true);
$o->suppliers()->detach([$so->id]);
return redirect()
->back()
->with('success','Supplier Deleted');
}
}