The relationship between users and courses and categories - laravel

I want to be able to see, for example, only a certain group that is in that category among the courses that I offer on the site.
Anyone can not see the course of another group
In this way, when registering, users choose the category they are in and see the information about their group in their profile.
Should I use polymorphic?
User table
Course table
Classification table
And another table called categorizable which is polymorphic how many to how many?
please guide me
database
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('slug');
$table->integer('parent')->default(0);
$table->foreignId('category_id')->nullable()->constrained('categories')->onDelete('cascade');
$table->timestamps();
});
Schema::create('categorizables' , function(Blueprint $table) {
$table->unsignedBigInteger('category_id');
$table->unsignedBigInteger('categorizable_id');
$table->string('categorizable_type');
});
model category
public function courses()
{
return $this->morphedByMany(Course::class , 'categorizable');
}
public function users()
{
return $this->morphedByMany(User::class , 'categorizable');
}
model user and course
public function categories()
{
return $this->morphToMany(Category::class, 'categorizable');
}
form blade
<form class="g-3" method="POST" action="{{ route('register') }}">
#csrf
<div class="col-8 m-auto">
<input type="text" required class="form-control #error('name') is-invalid #enderror" id="name" name="name">
#error('name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="col-8 m-auto">
<input type="text" required class="form-control #error('national_code') is-invalid #enderror" id="national_code" name="national_code">
#error('national_code')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="col-8 m-auto">
<select id="inputState" class="form-select" name="category_id">
<option selected class="d-none">select category</option>
#foreach(\App\Models\Category::all() as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>
</div>
<div class="col-8 m-auto">
<input type="password" required class="form-control #error('password') is-invalid #enderror" id="password" name="password">
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="col-8 m-auto">
<input type="password" required class="form-control #error('password_confirmation') is-invalid #enderror" id="password_confirmation" name="password_confirmation">
#error('password_confirmation')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<button type="submit">register</button>
</form>
controller
$data = $request->validate([
'name' => ['required', 'string', 'max:255'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
'national_code' => ['required' , New Nationalcode],
// 'g-recaptcha-response' =>['required' , New Recaptcha],
'category_id' => 'required',
]);
// $user = User::create($data);
$user = User::create([
'name' => $data['name'],
'password' => Hash::make($data['password']),
'national_code' => $data['national_code'],
// 'category_id' => $data['category_id'],
]);
$user->categories()->sync($data['category_id']);

Related

Cannot add data for second time but work for firs time, laravel add user

I'm trying to create a form to insert a user but the function doesn't work the second time, only the first. I got *rror after submitting it a second time.
302 found
UserController
class UserController extends Controller
{
// User
public function edit()
{
return view(
'pages.user.edit',
[
'user' => Auth::user(),
'title' => ''
]
);
}
public function create()
{
return view('pages.user.createUS', [
'levels' => Level::get(),
'perusahaans' => Perusahaan::get(),
'satkers' => Satker::get(),
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\Models\User
*/
public function store(Request $request)
{
// dd($validatedData);
$this->validate(request(), [
'name' => 'required',
'level_id' => 'required',
'satker_id' => 'required',
'username' => ['required', 'string', 'max:255', 'unique:users'],
'phonenumber' => ['required', 'unique:users'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
]);
$errors = $this->errors();
if ($this->fails()) {
return redirect('users/create')->withErrors($errors)->withInput()->with('err', true);
}
// dd($validatedData, $request);
$user = new User([
'name' => request('name'),
'username' => request('username'),
'email' => request('email'),
'phonenumber' => request('phonenumber'),
'level_id' => request('level_id'),
'satker_id' => request('satker_id'),
'remember_token' => Str::random(10)
]);
$user->password = md5(request('password'));
$user->save();
return redirect()->route('users.create')->with('success', 'User Berhasil Dibuat!');
}
/**
* Indicate that the model's email address should be unverified.
*
* #return static
*/
public function unverified()
{
return $this->state(function (array $attributes) {
return [
'email_verified_at' => null,
];
});
}
public function index()
{
$users = User::latest()->get();
$perusahaans = Perusahaan::get();
$satkers = Satker::latest()->get();
return view(
'pages.user.index',
[
'users' => $users,
'perusahaans' => $perusahaans,
'satkers' => $satkers,
'levels' => Level::get()
]
);
}
public function action(Request $request)
{
$pid = $request->post('pid');
$satkers = Satker::where('perusahaan_id', $pid)->latest()->get();
$html = '<option value="">Pilih Satuan Kerja</option>';
foreach ($satkers as $satker) {
$html .= '<option value="' . $satker->id . '">' . $satker->satker . '</option>';
}
echo $html;
// return response()->json(['html' => $html]);
}
// Setting Profile
public function show(User $user)
{
$details = DetailTransaksi::get();
$transaksis = Transaksi::latest()->get();
$tagihans = Tagihan::latest()->get();
$satkers = Satker::latest()->get();
// dd($tagihans->where('user_id', $user->id));
return view('pages.user.detail', [
'user' => $user,
'transaksis' => $transaksis,
'details' => $details,
'tagihans' => $tagihans,
]);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\User $user
* #return \Illuminate\Http\Response
*/
public function update(Request $request)
{
$user = Auth::user();
// $file_name = $request->image->getClientOriginalName();
$rules = [
'name' => 'required',
'username' => 'required',
'satker_id' => 'required',
'email' => 'required',
'phonenumber' => 'required',
'level_id' => 'required',
];
if (
$request->email != $user->email
) {
$rules['email'] = 'required|unique:users';
}
$validatedData = $request->validate($rules);
$validatedData['id'] = auth()->user()->id;
User::where('id', $user->id)
->update($validatedData);
return redirect('/user')->with('success', 'Profile has been Updated');
}
}
Blade
<section id="produk-form-create" class="">
<h4 class="fw-bold py-3 mb-4">
<span class="text-muted fw-light">User /</span> Tambah Data User
</h4>
<div class="col-xxl">
<div class="card mb-4">
<div class="card-header d-flex align-items-center justify-content-between">
<h5 class="mb-0">Form Tambah Produk</h5>
</div>
<div class="card-body">
<form action="/users/store" method="POST" enctype="multipart/form-data">
#csrf
<div class="row">
<div class="col-md-6 mb-3 text-start">
<label for="name" class="form-label">Nama User</label>
<input id="name" type="name" name="name" value="{{ old('name') }}"
class="form-control #error('name') is-invalid #enderror" required>
#error('name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="col-md-6 mb-3 text-start">
<label for="username" class="form-label">Username</label>
<input id="username" type="text" name="username" value="{{ old('username') }}"
class="form-control #error('username') is-invalid #enderror" required>
#error('username')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="col-md-6 mb-3 text-start">
<label for="email" class="form-label">Email</label>
<input id="email" name="email" value="{{ old('email') }}" type="text"
class="form-control #error('email') is-invalid #enderror" required>
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="col-md-6 mb-3 text-start">
<label for="leveluser" class="form-label">Level User</label>
<select class="form-select #error('leveluser') is-invalid #enderror" id="leveluser"
name="level_id" required>
#foreach ($levels as $level)
<option value="{{ $level->id }}">{{ $level->level }}</option>
#endforeach
</select>
#error('level_id')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="col-md-6 mb-3 text-start">
<label class="form-label" for="phonenumber">Phone Number</label>
<div class="input-group input-group-merge">
<span class="input-group-text">ID (+62)</span>
<input type="text" id="phonenumber" name="phonenumber" class="form-control"
placeholder="" value="{{ old('phonenumber') }}" required>
#error('phonenumber')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="col-md-6 mb-3 text-start">
<label for="perusahaan" class="form-label">Perusahaan</label>
<select class="form-select #error('perusahaan_id') is-invalid #enderror" id="perusahaan_id"
name="perusahaan_id" required>
#foreach ($perusahaans as $perusahaan)
<option value="{{ $perusahaan->id }}">{{ $perusahaan->nama_perusahaan }}
</option>
#endforeach
</select>
</div>
<input type="hidden" name="password" id="password" value="12345678">
<div class="col-md-6 mb-3 text-start">
<label for="password" class="form-label">Password</label>
<p>Password default untuk user adalah
<mark><strong
class="text-warning">"12345678"</strong></mark>
mohon arahkan kepada
user untuk mengganti password demi keamanan dan kenyamanan bersama.
</p>
</div>
<div class="col-md-6 mb-3 text-start">
<label for="satker_id" class="form-label">Satuan Kerja</label>
<select id="satker_id" name="satker_id"
class="form-select #error('satker') is-invalid #enderror" required>
#foreach ($satkers->where('perusahaan_id', 1) as $satker)
<option value="{{ $satker->id }}">
{{ $satker->satker }}
</option>
#endforeach
</select>
#error('satker_id')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row">
<div class="col-sm-4 ">
<button type="submit" class="btn btn-primary"><i class="fw-icons bx bx-send"></i>
Send
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</section>
Routes
Route::get('users', [UserController::class, 'index'])->name('users')->middleware('userlevel');
Route::get('users/{user}/edit', [UserController::class, 'edit'])->name('users.edit')->middleware('userlevel');
Route::get('users/create', [UserController::class, 'create'])->name('users.create')->middleware('userlevel');
Route::post('/users/store', [UserController::class, 'store'])->name('users.store')->middleware('userlevel');
Route::delete('users/{user}/destroy', [UserController::class, 'destroy'])->name('users.destroy')->middleware('userlevel');
Route::put('users/{user}/update', [UserController::class, 'update'])->name('users.destroy')->middleware('userlevel');
Route::post('users/action', [UserController::class, 'action']);
Success in the first-time post but get 302 found in the second time. Please help me to solve this problem.

Route [staff] not defined while it is in laravel?

Route [staff] not defined.
This is my web.php (route).
Route::get('/staff', function () {
return view('staff');
});
Route::resource('/staff', StaffController::class);
This is my controller. The index, create page is in same page.
public function index()
{
$staffs = Staff::all();
return view('staff', compact('staffs'));
}
public function create()
{
return view('staff');
}
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'gender' => 'required',
'salary' => 'required',
]);
$staff = new Staff();
$staff->name = $request->name;
$staff->gender = $request->gender;
$staff->salary = $request->salary;
$staff->save();
return redirect()->route('staff')->withSuccess('Done');
}
And this is my staff.blade.php where after click on submit error occuring (route not defined).
<form id="myForm" method="post" action="{{ route('staff.store') }}">
#csrf
<div class="user-box">
<input type="text" name="name" required="">
<label>Name</label>
#error('name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="user-box">
<input type="text" name="gender" required="">
<label>Gender</label>
#error('gender')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="user-box">
<input type="text" name="salary" required="">
<label>Salary</label>
#error('salary')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<button class="a" id="a" value="submit" name="submit">Submit</button>
</form>
There are no any name route called staff, it would be staff.index :
return redirect()->route('staff.index')->withSuccess('Done');
See Resource Route Name
1st remove your get route all is covered by resource
Route::resource('/staff', StaffController::class);
this code generate route names like
Route Name
staff.index
staff.create
staff.store
staff.show
staff.edit
staff.update
staff.destroy
so in your code you need to do this
return redirect()->route('staff.index')->withSuccess('Done');
ref link https://laravel.com/docs/8.x/controllers#actions-handled-by-resource-controller

Reset password manually via answering the security questions without sending email - Laravel/auth

I am currently developing a simple Bookstore application with a few numbers of users on which sending emails are not needed because it will be implemented in local system so is there any way to customize laravel-auth for password reset function by adding a few security questions fields where user can reset his/her password without sending reset links via email.
Any kind of help will be highly appreciated.
here I tried the below code but id did not work
Code in web.php
Route::post('/main/checklogin', 'UserController#chekQuestions');
Code in userContoller
public function chekQuestions(Request $request)
{
$request->validate( [
'email' => 'required|string|email',
'answerQuestionOne' => 'required|string|confirmed',
'answerQuestionTwo' => 'required|string'
] );
$user = User::first();
if($user->email == $request->email && $user->answerQuestionOne == $request->answerQuestionOne && $user->answerQuestionTwo == $request->answerQuestionTwo )
{
// $userEmail = DB::table( 'password_resets' )->where( 'token', $user->token );
// return view('auth.password.reset',compact($userEmail));
return view('auth.password.reset');
}
return response()->json( [
'error' => true,
'message' => 'We cannot find a user with that Email Address'
], 404 );
}
Code in reset password.blade
<div id="register" class="animate form registration_form">
<section class="login_content">
<form method="POST" action="{{ url('/main/checklogin') }}" >
#csrf
<h3>د پټ نو بیا راګرځولو لپاره لاندی امنتی پوښتنو ته ځواب ورکړی </h3>
<div class="form-group has-feedback">
<input id="email" type="email" placeholder=" ایمل" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
<div class="form-control-feedback">
<i class="fa fa-envelope-o text-muted"></i>
</div>
</div>
<div>
<input id="answerQuestionOne" placeholder="لومړۍ امنیتي پوښتنه" type="text" class="form-control #error('answerQuestionOne') is-invalid #enderror" name="answerQuestionOne" value="{{ old('answerQuestionOne') }}" required autocomplete="answerQuestionOne" autofocus>
#error('answerQuestionOne')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div>
<input id="answerQuestionTwo" placeholder="دوهمه امنیتي پوښتنه " type="text" class="form-control #error('answerQuestionTwo') is-invalid #enderror" name="answerQuestionTwo" value="{{ old('answerQuestionTwo') }}" required autocomplete="answerQuestionTwo" autofocus>
#error('answerQuestionTwo')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<button type="submit" class="btn btn-default btn-block">خوندی کړی </button>
<div class="clearfix"></div>
<div class="separator">
<p class="change_link">
تاسو دمخه غړی یاست ننوتل
</p>
<div class="clearfix"></div>
<br />
</form>
</section>
</div>
You don't need Laravel implementation for this. Just Find a user with the given email and check the answers. After that update the user record with the new password.
In order to fetch user you should do this:
$data = $request->validate( [
'email' => 'required|string|email',
'answerQuestionOne' => 'required|string|confirmed',
'answerQuestionTwo' => 'required|string'
] );
$user = User::where(['email' => $data['email'])->first();
After this just check the answers.
You also need to take the new password from user.

How to change password?

I want to edit form update only address, email and password. How to change password? The old password is important.
edit.blade.php
<form method="POST" action="{{ route('update') }}">
#csrf
{{ method_field('PATCH') }}
<div class="form-group row">
<label for="email" class="col-md-1 col-form-label text-md-right">{{ __('Email') }}</label>
<div class="col-md-5">
<input id="email" type="text" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') ? : user()->email }}" required autocomplete="email" autofocus>
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-1 col-form-label text-md-right">{{ __('Password') }}</label>
<div class="col-md-5">
<input id="password" type="text" class="form-control #error('password') is-invalid #enderror" name="password" value="{{ old('password') }}" required autocomplete="password" autofocus>
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="address" class="col-md-1 col-form-label text-md-right">{{ __('Address') }}</label>
<div class="col-md-5">
<textarea id="address" type="text" class="form-control #error('address') is-invalid #enderror" name="address" required autocomplete="address" autofocus>{{ old('address') ? : user()->address }}</textarea>
#error('address')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-1">
<button type="submit" class="btn btn-block btn-primary">
{{ __('Register') }}
</button>
</div>
</div>
</form>
Route
Route::post('update', 'Auth\RegisterController#sqlupdate')->name('update');
RegisterController
public function sqlupdate(Request $request)
{
Auth::user()->update([
'address' => $request['address'],
'email' => $request['email'],
]);
$hashedPassword = auth()->user()->password;
if (Hash::check($request->oldpassword, $hashedPassword)){
$user = User::findOrFail(Auth::id());
$user->password = Hash::make($request->password);
}
return redirect()->back();
}
Just read the below code carefully :-
/**
* Admin My profile : Password update.
*
* #param Request $request
* #param $id
* #return \Illuminate\Http\Response
*/
public function updatePassword(Request $request,$id = 0)
{
$validate = Validator::make($request->all(),[
'old_password' => 'required',
'password' => 'required|confirmed|min:8',
'password_confirmation' => 'required|min:8',
]);
$getUserData = Admin::where('id',$id)->first();
if($getUserData === null) {
return redirect()->back()->with([
'status' => 'warning',
'title' => 'Warning!!',
'message' => 'Invalid Admin ID.'
]);
}
$validate->after(function ($validate) use ($request,$getUserData,$id) {
if(!Hash::check($request->get('old_password'),$getUserData->password)){
$validate->errors()->add('old_password', 'Wrong old password');
}
});
if($validate->fails()){
return redirect()->back()->withErrors($validate)->withInput();
}
try{
$getUserData->update([
'password' => Hash::make($request->get('password'))
]);
return redirect()->back()->with([
'status' => 'success',
'title' => 'Success!!',
'message' => 'Admin password updated successfully.'
]);
}catch (Exception $e){
return redirect()->back()->with([
'status' => 'error',
'title' => 'Error!!',
'message' => $e->getMessage()
]);
}
}
With the above method you'll get the idea of how we update password, this is from one of my project i've created three field for that here is the screenshot of view :-
I hope this will help
Further more update here is the small snippet for update method
specially
$getOldPassword = User::where('id',$id)->first();
if($request->get('password') === null){
$password = $getOldPassword->password;
}else{
$password = Hash::make($request->get('password'));
}

Laravel always sets the default value

I am trying to do registration with user profile picture upload.(I am forced to do it this way)
I created the migration like this:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('nom');
$table->string('prenom');
$table->string('type')->default('visiteur');
$table->boolean('confirme')->default(false);
$table->string('email')->unique();
$table->string('password');
$table->string('photo_url')->default('default_photo_profile.jpg');
$table->rememberToken();
$table->timestamps();
});
the create function :
$request = request();
if ($request->hasFile('photo')) {
$file = $request->file('photo');
$fullname=$data['nom'].'_'.date("Y-m-d",time()).'.'.$file->getClientOriginalExtension();
$path = $request->file('photo')->storeAs('images', $fullname);
}
return User::create([
'nom' => $data['nom'],
'prenom' => $data['prenom'],
'email' => $data['email'],
'photo_url' => $fullname,
'password' => Hash::make($data['password']),
]);
}
and the form for the file field is like this:
<div class="form-group">
<label for="photo_url">Photo profile</label>
<input type="file" name="photo" class="form-control-file" id="photo_url">
</div>
everything is working fine except the photo_url field, it always sets the default value in the migration and not the value I set in the create function.
$fullname is initiated and already declared.
the entire form :
<form method="POST" action="{{ route('register') }}" aria-label="{{ __('Register') }}" enctype="multipart/form-data">
#csrf
<div class="form-group row">
<label for="nom" class="col-md-4 col-form-label text-md-right">Nom</label>
<div class="col-md-6">
<input id="nom" type="text" class="form-control{{ $errors->has('nom') ? ' is-invalid' : '' }}" name="nom" value="{{ old('nom') }}" required autofocus>
#if ($errors->has('nom'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('nom') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="prenom" class="col-md-4 col-form-label text-md-right">Prénom</label>
<div class="col-md-6">
<input id="prenom" type="text" class="form-control{{ $errors->has('prenom') ? ' is-invalid' : '' }}" name="prenom" value="{{ old('prenom') }}" required autofocus>
#if ($errors->has('prenom'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('prenom') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">Email</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="email" value="{{ old('email') }}" required>
#if ($errors->has('email'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">Mot de pass</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control{{ $errors->has('password') ? ' is-invalid' : '' }}" name="password" required>
#if ($errors->has('password'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="password-confirm" class="col-md-4 col-form-label text-md-right">Mot de pass confirmation</label>
<div class="col-md-6">
<input id="password-confirm" type="password" class="form-control" name="password_confirmation" required>
</div>
</div>
<div class="form-group">
<label for="photo_url">Photo profile</label>
<input type="file" name="photo" class="form-control-file" id="photo_url">
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
Envoyer
</button>
</div>
</div>
</form>
What is the problem?
Assuming you have a value for $photo_url, make sure you have 'photo_url' in your $fillables.
When you have $fillables, it only inserts (via User::create) what has in that array, otherwise it doesn't submit for that variable.
Your $fillables should look like this:
$fillables = ['nom','prenom','type','confirme','email','password','photo_url'];
Add 'photo' in $fillable array in User model:
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'photo_url',
];
so according to your code in your model you have to add the photo_url in $fillable array like below.
$fillables = ['nom','prenom','type','confirme','email','password','photo_url'];
okay now there are 3 ways to do it with $fillable is first way and you are doing it right now.
2nd way:
if ($request->hasFile('photo')) {
$file = $request->file('photo');
$fullname=$data['nom'].'_'.date("Y-m-d",time()).'.'.$file->getClientOriginalExtension();
$path = $request->file('photo')->storeAs('images', $fullname);
}
else
{
$fullname = "default_photo_profile.jpg";
}
return User::create([
'nom' => $data['nom'],
'prenom' => $data['prenom'],
'email' => $data['email'],
'photo_url' => $fullname,
'password' => Hash::make($data['password']),
]);
and in your migration change this $table->string('photo_url')->default('default_photo_profile.jpg'); to $table->string('photo_url');
3rd way:
$fullname = "default_photo_profile.jpg";
if ($request->hasFile('photo')) {
$file = $request->file('photo');
$fullname=$data['nom'].'_'.date("Y-m-d",time()).'.'.$file->getClientOriginalExtension();
$path = $request->file('photo')->storeAs('images', $fullname);
return User::create([
'nom' => $data['nom'],
'prenom' => $data['prenom'],
'email' => $data['email'],
'photo_url' => $fullname,
'password' => Hash::make($data['password']),
]);
}
return User::create([
'nom' => $data['nom'],
'prenom' => $data['prenom'],
'email' => $data['email'],
'photo_url' => $fullname,
'password' => Hash::make($data['password']),
]);
}
okay these are the ways to do it. i would prefer first and second way 3rd one is lengthy.
Note: for 2nd and 3rd case you have to change your migration from this $table->string('photo_url')->default('default_photo_profile.jpg'); to $table->string('photo_url');
Hope you get it.

Resources