Files
airline-agency/app/Http/Controllers/Auth/RegisterController.php
T

116 lines
3.3 KiB
PHP

<?php
namespace App\Http\Controllers\Auth;
use App\Enums\User\UserStatus;
use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\RegisterPostRequest;
use App\Models\Country;
use App\Models\File;
use App\Models\Province;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
class RegisterController extends Controller
{
public function index()
{
$title = 'ثبت نام';
$withOutHeader = true;
$withOutFooter = true;
$iranCountry = Country::where('name', 'iran')->first();
$provinces = Province::where('status', 1)
->whereHas('cities', function ($query) use ($iranCountry) {
$query->where('county_id', $iranCountry->id);
})
->orderBy('name')
->pluck('name', 'id');
return view('auth.register' , compact('title' , 'withOutHeader' , 'withOutFooter' , 'provinces'));
}
public function post(RegisterPostRequest $request)
{
$data = $request->validated();
DB::beginTransaction();
try {
$fileId = null;
if ($request->hasFile('avatar')) {
$image = $request->file('avatar');
$imageName = time() . '_' . rand(11111, 99999) . '.' . $image->extension();
$path = $image->storeAs(
'user_avatar',
$imageName,
'public'
);
$file = File::create([
'name' => $imageName,
'original_name' => $image->getClientOriginalName(),
'extension' => $image->extension(),
'size' => $image->getSize(),
'path' => $path,
]);
$fileId = $file->id;
}
$user = User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'file_id' => $fileId,
'province_id' => $data['province_id'] ?? null,
'city_id' => $data['city_id'] ?? null,
'national_code' => $data['national_code'],
'gender' => $data['gender'],
'marital_status' => $data['marital_status'],
'spouse_name' => $data['spouse_name'] ?? null,
'mobile' => $data['mobile'],
'email' => $data['email'],
'username' => $data['username'],
'password' => Hash::make($data['password']),
'status' => UserStatus::ENABLE->value,
]);
DB::commit();
Auth::login($user);
return redirect()
->route('index')
->with('success', 'ثبت‌نام شما با موفقیت انجام شد.');
} catch (\Exception $exception) {
DB::rollBack();
if (isset($path) && Storage::disk('public')->exists($path)) {
Storage::disk('public')->delete($path);
}
return back()
->withInput()
->with('error', 'ثبت‌نام با خطا مواجه شد. لطفاً دوباره تلاش کنید.');
}
}
}