error message not appearing, validate array - laravel

Please help me showing my error message, array message not appears in table
$validation_file = $this->validate([
'requirements' => 'required|array',
'requirements.*' => 'required|array',
'requirements.*.file' => 'required|mimes:pdf,jpg,png,jpeg|max:20000|array',
'input.*.input' => 'required|array',
'requirements.*.file.input' => 'required|array',
]);
Blade
<input type="hidden" name="req_id[{{ $key }}]" wire:model="req_id.{{ $key }}.id" value="{{ $requirements->id }}">
<input type='file' wire:model="requirement.{{ $requirements->id }}.file" class="form-control" accept=".pdf">
#error('requirements.{{ $key }}.file')
<div class="invalid-feedback">{{ $message }}</div>
#enderror
<input type="hidden" name="req_id[{{ $key }}]" wire:model="req_id.{{ $key }}.id" value="{{ $input->id }}">
<input type='text' wire:model.defer="input.{{ $input->id }}.input" class="form-control">
#error('input.{{ $key }}.input')
<div class="invalid-feedback">{{ $message }}</div>
#enderror

Your wire:model has a spelling error:
wire:model="requirement.{{ $requirements->id }}.file"
It should be (notice the missing s):
wire:model="requirements.{{ $requirements->id }}.file"

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.

How can I pre-fill form data entered by a user in Laravel 7

I'm making a registration form where users will be redirected to a preview page to confirm their details first before submitting the form. I'm using Laravel 7 and I'm quite new to Laravel. Once the user enters their details in registration form, the same details will be pre-filled in the preview form before submission. I have tried some code in my controller but it's giving me an error Trying to get property 'myForm' of non-object In my Controller, $data is an array, I'm not sure how I can achieve this. Please help.
In my Conroller:
public function confirmation(Request $request)
{
$categories = Category::all();
$request->validate([
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'telephone_number' => 'required|digits:10',
'email' => 'required|string|email|max:255|unique:users','regex:/^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,6}$/',
'password' => 'required|string|min:6|confirmed',
'password_confirmation' => 'required',
'region' => 'required|string',
'description' => 'required|string|max:2500',
'start_date' => 'required|date',
'client_region' => 'string|max:500',
'client_category' => 'integer|max:255',
]);
$data['myForm'] = $request->all();
return view('auth.client.preview', compact('categories', 'data'));
}
In my blade view:
<div class="form-group">
<label for="first_name">First Name</label><span class="text-danger">*</span>
<input type="text" class="form-control{{ $errors->has('first_name')?'is-invalid':'' }}"
name="first_name" value="{{$data->myForm['first_name']}}"
placeholder="Enter First Name" autofocus tabindex="1" required>
<div class="invalid-feedback">
{{ $errors->first('first_name') }}
</div>
</div>
My Route:
Route::post('/preview-details', 'Auth\Client\PreviewRegisterDetailsController#confirmation')->name('preview-details');
Dropdown List:
<label for="fundi_type">Fundi Type</label><span class="text-danger">*</span>
<select class="custom-select" id="category_id" name="category_id">
#foreach($categories as $category )
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>
Simplify like this below .So no need to create extra array key .
$myForm = $request->all();
return view('auth.client.preview', compact('categories', 'myForm'));
and in view
<input type="text" class="form-control{{ $errors->has('first_name')?'is-invalid':'' }}"
name="first_name" value="{{$myForm['first_name']}}"
placeholder="Enter First Name" autofocus tabindex="1" required>
Updated
<option value="{{ $category->id }}" {{($myForm['category_id']==$category->id)?'selected':null}}>{{ $category->name }}</option>
Edit your blade file code.
Actually your controller is sending array and you are accessing that array as a collection.
From :
<input type="text" class="form-control{{ $errors->has('first_name')?'is-invalid':'' }}"
name="first_name" value="{{$data->myForm['first_name']}}"
placeholder="Enter First Name" autofocus tabindex="1" required>
To
<input type="text" class="form-control{{ $errors->has('first_name')?'is-invalid':'' }}"
name="first_name" value="{{$data['myForm']['first_name']}}"
placeholder="Enter First Name" autofocus tabindex="1" required>
Hope this will be useful.

Check if at least one input has value with laravel controller

I have a simple form where the user should be able to only fill the inputs he wants but if the form hasn't at least one input filled, it should return a error message saying that the form can't be empty if he clicks the submit button.
Here's my form:
#if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<strong>{{ $message }}</strong>
</div>
#endif
</center>
<form action="{{ route('send-update') }}" method="POST" enctype="multipart/form-data"> #csrf
<label>Nome do projeto:</label>
<div class="input-group mb-3"><br>
<input type="text" class="form-control" name="project_name" aria-label="Username" aria-describedby="basic-addon1">
</div>
#error('project_name')
<div class="text-danger" style="float:left; margin-top:-10px" role="alert">
<small> {{$message}}</small>
</div>
#enderror
<br>
<label>Descrição:</label>
<div class="input-group mb-3"><br>
<textarea class="form-control" name="desc" aria-label="With textarea"></textarea>
</div>
#error('desc')
<div class="text-danger" style="float:left; margin-top:-10px" role="alert">
<small> {{$message}}</small>
</div>
#enderror
<br>
<label>Tem alguma imagem que queira mudar/inserir?</label>
<div class="input-group mb-3">
<input type="file" name="img" accept="image/*" class="form-control" id="inputGroupFile01">
</div>
#error('img')
<div class="text-danger" style="float:left; margin-top:-10px" role="alert">
<small> {{$message}}</small>
</div>
#enderror
<div class="input-group mb-3">
<input type="text" class="form-control" name="img_desc" placeholder="Diga-nos onde pretende mudar/adicionar">
</div>
#error('img_desc')
<div class="text-danger" style="float:left; margin-top:-10px" role="alert">
<small> {{$message}}</small>
</div>
#enderror
<br>
<label>Tem mais informações? Insira um arquivo .txt, docx ou pdf</label>
<div class="input-group mb-3">
<input type="file" name="ficheiro" accept=".xlsx,.xls,.doc, .docx,.ppt, .pptx,.txt,.pdf" class="form-control" id="inputGroupFile01">
</div>
#error('ficheiro')
<div class="text-danger" style="float:left; margin-top:-10px" role="alert">
<small> {{$message}}</small>
</div>
#enderror
<br>
<input type="hidden" name="id" value="{{ request('id') }}">
<center> <button type="submit" class="btn btn-secondary ">Fazer pedido de atualização</button></center><br>
</form>
And here's the controller:
public function sendUpdate(Request $request){
$id = $request['id'];
$order = Order::where('id', $id)->first();
$validator = Validator::make($request->all(), [
'project_name' => ['nullable', 'string', 'max:255', 'regex:/^[a-zA-Z]+$/u]'],
'desc' => ['nullable', 'string', 'max:255', 'regex:/^[a-zA-Z]+$/u]'],
'img' => ['nullable', 'image', 'mimes:jpeg,png,jpg,svg', 'max:1024'],
'img_desc' => ['nullable', 'string', 'max:255', 'regex:/^[a-zA-Z]+$/u]'],
'ficheiro' => ['nullable', 'csv,txt,xlx,xls,pdf', 'max:2048'],
]);
if (request()->hasFile('ficheiro')){
if (request()->file('ficheiro')->isValid())
{
$fileName = $request->file('ficheiro')->getClientOriginalName();
$path = $request->file('ficheiro')->storeAs('files', $fileName, 'public');
}}
if (request()->hasFile('img')){
if (request()->file('img')->isValid())
{
$imageName = $request->file('img')->getClientOriginalName();
$pathImg = $request->file('img')->storeAs('files', $imageName, 'public');
}}
Update::create([
'customer_name' => $order->customer_name,
'customer_email' => $order->email,
'project_name' => $order->project_name,
'project_new_name' => $request['project_name'],
'description' => $request['desc'],
'image' => $pathImg ?? '',
'image_desc' => $request['img_desc'],
'ficheiro' => $path ?? '',
]);
return back()->with('success','Obrigado! Entraremos em contacto consigo em breve!');
}
I have no idea how to check if all inputs are empty in the controller . I've already tried this below, but it doesn't work. It keeps sending the form anyway.
if(count($request->all()) < 0) {
return dd('request all input empty.');
}
You can do it this way.
if(empty(array_filter($request->all()))){
//All fields are empty.
}

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