Laravel update only refreshes a page - php

My update page isn't working, when I'm submitting a form it only refreshes a page and adds some stuff to my URL, for example: http://127.0.0.1:8000/admin/employees/102/edit?_method=PUT&_token=mj3lrHqoYm1wiLwWiNQ8OX0kNRjmW4QVRuLpgZxY&image_path=&name=Libbie+Ebert&phone_number=380324244497&email=brekke.lola%40example.org&position_id=7&payment=186799&head=Asia+Frami&recruitment_date=2022-01-10. I already cleared route cache and its still not working, and also tried to use dd function but it's not showing up. What can be wrong? My model:
class Employee extends Model
{
use HasFactory;
protected $casts = [
'recruitment_date' => 'datetime:d-m-y',
];
protected $fillable= ['name', 'position_id', 'phone_number',
'recruitment_date', 'email', 'head',
'image_path', 'payment', 'admin_created_id', 'admin_updated_id'];
public function position()
{
return $this->belongsTo(Position::class, 'position_id');
}
}
Controller function:
public function update(StoreEmployeeRequest $request, $id){
$input = $request->validated();
$employee = Employee::findOrFail($id);
$employee->update([
'name' => $request->input('name'),
'position_id' => $request->input('position_id'),
'phone_number' => '+' . $request->input('phone_number'),
'recruitment_date' => $request->input('recruitment_date'),
'email' => $request->input('email'),
'head' => $request->input('head'),
'image_path' => $input['image_path'],
'payment' => number_format($request->input('payment')),
'admin_updated_id' => auth()->id(),
]);
return to_route('admin.employees.index');
}
Request:
public function rules()
{
return [
'name' => 'required|min:2|max:255',
'recruitment_date' => 'required|date',
'phone_number' => 'required',
'email' => 'required|email',
'payment' => 'required|numeric',
'position_id' => 'required',
'image_path' => 'image|mimes:jpg,png|max:5000|dimensions:min_width=300,min_height=300'
];
}
View:
<form action="{{ route('admin.employees.update', ['id' => $employee->id]) }}" enctype="multipart/form-data">
#method('PUT')
#csrf
<label for="image_path" class="form-label">Photo</label>
<input type="file" name="image_path" class="form-control-file" >
#error('image_path')
<div class="alert alert-danger mt-2" role="alert"><strong>{{ $message }}</strong></div>
#enderror
<label for="name" class="form-label">Name</label>
<input type="text" name="name" class="form-control" value="{{ $employee->name }}" placeholder="Name is...">
#error('name')
<div class="alert alert-danger mt-2" role="alert"><strong>{{ $message }}</strong></div>
#enderror
<label for="phone_number" class="form-label">Phone</label>
<input type="text" name="phone_number" class="form-control" value="{{ old('phone_number', preg_replace('/[^0-9]/', '', $employee->phone_number)) }}" placeholder="380...">
#error('phone_number')
<div class="alert alert-danger mt-2" role="alert"><strong>{{ $message }}</strong></div>
#enderror
<label for="email" class="form-label">Email</label>
<input type="email" name="email" class="form-control" value="{{ old('email', $employee->email) }}" placeholder="Email is...">
#error('email')
<div class="alert alert-danger mt-2" role="alert"><strong>{{ $message }}</strong></div>
#enderror
<label for="position_id" class="form-label">Position</label>
<select class="form-control" name="position_id" aria-label=".form-select-lg example">
#foreach ($positions as $position)
<option value="{{ $position->id }}" {{$employee->position_id == $position->id ? 'selected' : ''}}>{{ $position->name }}</option>
#endforeach
</select>
#error('position_id')
<div class="alert alert-danger mt-2" role="alert"><strong>{{ $message }}</strong></div>
#enderror
<label for="payment" class="form-label">Salary, $</label>
<input type="text" name="payment" class="form-control" value="{{ old('payment', preg_replace('/[^0-9]/', '', $employee->payment)) }}" placeholder="Salary is...">
#error('payment')
<div class="alert alert-danger mt-2" role="alert"><strong>{{ $message }}</strong></div>
#enderror
<label for="head" class="form-label">Head</label>
<input type="text" id="head" name="head" class="form-control" value="{{ old('head', $employee->head) }}" placeholder="Head is...">
#error('head')
<div class="alert alert-danger mt-2" role="alert"><strong>{{ $message }}</strong></div>
#enderror
<label for="recruitment_date" class="form-label">Date</label>
<input type="datetime-local" name="recruitment_date" value="{{ old('recruitment_date', $employee->recruitment_date) }}" class="form-control">
#error('recruitment_date')
<div class="alert alert-danger mt-2" role="alert"><strong>{{ $message }}</strong></div>
#enderror
<div class="mt-4 text-center">
<button type="submit" class="btn btn-secondary">Submit</button>
</div>
</form>
Route:
Route::put('/admin/employees/{id}/edit', [EmployeeController::class, 'update'])->name('admin.employees.update');

You are missing the method attribute in your form, and the default one is GET. Adding #method('PUT') is not enough.
Change your code like this:
<form
action="{{ route('admin.employees.update', ['id' => $employee->id]) }}"
method="POST"
enctype="multipart/form-data">

i think you should you POST method while submitting the form.

Related

How do I keep the value of a checkbox in an invalid form in this Laravel 8 application?

I am working on a Laravel 8 blogging application. The "Add article" form has a "switch" (checkbox) that lets the user choose whether or not the post will be a featured one.
The form:
<form method="POST" action="{{ route('dashboard.articles.add') }}" enctype="multipart/form-data" novalidate>
#csrf
<div class="col-md-12 #error('title') has-error #enderror">
<input id="title" type="text" placeholder="Title" class="form-control #error('title') is-invalid #enderror" name="title" value="{{ old('title') }}" autocomplete="title" autofocus>
#error('title')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="row mb-2">
<label for="short_description" class="col-md-12">{{ __('Short description') }}</label>
<div class="col-md-12 #error('short_description') has-error #enderror">
<input id="short_description" type="text" placeholder="Short description" class="form-control #error('short_description') is-invalid #enderror" name="short_description" value="{{ old('short_description') }}" autocomplete="short_description" autofocus>
#error('short_description')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row mb-2">
<label for="category" class="col-md-12">{{ __('Category') }}</label>
<div class="col-md-12 #error('category_id') has-error #enderror">
<select name="category_id" id="category" class="form-control #error('category_id') is-invalid #enderror">
<option value="0">Pick a category</option>
#foreach($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>
#error('category_id')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row mb-2">
<div class="col-md-12 d-flex align-items-center switch-toggle">
<p class="mb-0 me-3">Featured article?</p>
<input id="featured" class="mt-1" type="checkbox" name="featured">
<label class="px-1" for="featured">{{ __('Toggle') }}</label>
</div>
</div>
<button type="submit" class="w-100 btn btn-primary">{{ __('Save') }}</button>
</form>
The controller:
class ArticleController extends Controller
{
private $rules = [
'category_id' => 'required|exists:article_categories,id',
'title' => 'required|string|max:190',
'short_description' => 'required|string|max:190',
];
private $messages = [
'category_id.required' => 'Please pick a category for the article',
'title.required' => 'Please provide a title for the article',
'short_description.required' => 'The article needs a short description',
'short_description.max' => 'The short description field is too long',
];
public function categories() {
return ArticleCategory::all();
}
public function create() {
// Load the view and populate the form with categories
return view('dashboard/add-article',
['categories' => $this->categories()]
);
}
public function save(Request $request) {
// Validate form (with custom messages)
$validator = Validator::make($request->all(), $this->rules, $this->messages);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator->errors())->withInput();
}
$fields = $validator->validated();
// Turn the 'featured' field value into a tiny integer
$fields['featured'] = $request->get('featured') == 'on' ? 1 : 0;
// Data to be added
$form_data = [
'user_id' => Auth::user()->id,
'category_id' => $fields['category_id'],
'title' => $fields['title'],
'slug' => Str::slug($fields['title'], '-'),
'short_description' => $fields['short_description'],
'featured' => $fields['featured'],
];
// Insert data in the 'articles' table
$query = Article::create($form_data);
if ($query) {
return redirect()->route('dashboard.articles')->with('success', 'The article titled "' . $form_data['title'] . '" was added');
} else {
return redirect()->back()->with('error', 'Adding article failed');
}
}
}
The problem
When an attempt is made to submit the invalid form, the fields that are valid keep their values.
The unintended exception to the rule is the checkbox <input id="featured" class="mt-1" type="checkbox" name="featured">
What is my mistake?
Your input has no value, so you can only check on existence not on value in controller ($request->get('featured') will never have the value on)
You need to use old('featured') on that field too
You can skip the check on the featured field in the controller if you set the values to 0 and 1 in the form
<div class="row mb-2">
<div class="col-md-12 d-flex align-items-center switch-toggle">
<p class="mb-0 me-3">Featured article?</p>
<input type="hidden" value="0" name="featured">
<input {{ old('featured') ? 'checked':'' }} id="featured" value="1" class="mt-1" type="checkbox" name="featured">
<label class="px-1" for="featured">{{ __('Toggle') }}</label>
</div>
</div>
The hidden field is to send the value 0 if the checkbox is not checked. A checkbox input is not sent in the request if it is not checked.
When checked, the input value will be overwritten to 1.
In the controller you can directly use the input
$fields = $validator->validated();
// Data to be added
$form_data = [
'user_id' => Auth::user()->id,
'category_id' => $fields['category_id'],
'title' => $fields['title'],
'slug' => Str::slug($fields['title'], '-'),
'short_description' => $fields['short_description'],
'featured' => $fields['featured'],
];

Why create function in RegisterController is not working in laravel

I am new to Laravel. I am using registerController in Laravel to create users . Users data are stored in Users table.
What I have tried is :
#extends('adminlte::auth.auth-page', ['auth_type' => 'register'])
#php( $login_url = View::getSection('login_url') ?? config('adminlte.login_url', 'login') )
#php( $register_url = View::getSection('register_url') ?? config('adminlte.register_url', 'register') )
#if (config('adminlte.use_route_url', false))
#php( $login_url = $login_url ? route($login_url) : '' )
#php( $register_url = $register_url ? route($register_url) : '' )
#else
#php( $login_url = $login_url ? url($login_url) : '' )
#php( $register_url = $register_url ? url($register_url) : '' )
#endif
#section('auth_header', __('adminlte::adminlte.register_message'))
#section('auth_body')<!-- comment -->
<?php $roles = DB::table('roles')->where('id','>',1)->get(); ?>
<div class="login-form">
<div class="container">
<div class="row ">
<div class="register-box">
<div class="register-box-header">
<p class="login-box-msg">{{!empty($type) && $type == 'Agronamist' ? 'Buyer' : ''}} REGISTRATION FORM</p>
</div>
<div class="register-box-body register_body">
<form method="POST" action="{{ route('register') }}" class="registerForm" enctype="multipart/form-data">
#csrf
#if(empty($type))
<div class="row">
<div class="col-md-12 text-center">
<div class="form-group has-feedback">
<select name="role" class="form-control" onchange='window.location.href=window.location.origin+"/register?role="+$(this).val();' required>
<option value="">Select a Role</option>
#foreach($roles as $role)
<option value="{{$role->id}}" {{(count($_GET)>0 && $_GET['role'] == $role->id) ? 'selected' : ''}}>{{$role->name}} </option>
#endforeach
</select>
</div>
</div>
</div>
#else
<input type="hidden" name="role" value="2">
<input type="hidden" name="type" value="{{$type}}">
#endif
#if(count($_GET)>0 && $_GET['role'] != '')
<?php $states = DB::table('states')->orderBy('name','asc')->get();?>
<div class="row">
<div class="col-md-6">
<div class="form-group has-feedback">
<input type="text" class="form-control" placeholder="First Name *" name="first_name" value="{{ old('first_name') }}" required>
<span class="glyphicon glyphicon-user form-control-feedback"></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group has-feedback">
<input type="text" class="form-control" placeholder="Last Name *" name="last_name" value="{{ old('last_name') }}" required>
<span class="glyphicon glyphicon-user form-control-feedback"></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group has-feedback">
<input type="email" class="form-control" name="email" value="{{ old('email') }}" placeholder="Email *" required>
<span class="glyphicon glyphicon-envelope form-control-feedback"></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group has-feedback">
<input type="text" class="form-control phoneMask" placeholder="Phone *" name="phone" value="{{ old('phone') }}" required>
<span class="glyphicon glyphicon-phone form-control-feedback"></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group has-feedback">
<input type="text" class="form-control" placeholder="Address *" name="address" value="{{ old('address') }}" required>
<span class="glyphicon glyphicon-map-marker form-control-feedback"></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group has-feedback">
<input type="password" class="form-control #error('password') is-invalid #enderror" name="password" placeholder="Password *" required autocomplete="new-password">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="col-md-6">
<div class="form-group has-feedback">
<input type="password" class="form-control" name="password_confirmation" placeholder="Retype password *" required autocomplete="new-password">
<span class="glyphicon glyphicon-log-in form-control-feedback"></span>
</div>
</div>
<div class="row">
<div class="col-md-3 col-xs-offset-4 submit_btn">
<button type="submit" class="btn btn-primary btn-block btn-flat">Register</button>
</div>
</div>
#endif
</form>
Register Controller
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\manager_group;
use App\User;
use App\UserAddresses;
use App\UserDetails;
use App\UserRoles;
use Auth;
use DB;
use Illuminate\Auth\Events\Registered;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
use RegistersUsers;
protected $redirectTo = '/';
public function __construct()
{
//$this->middleware('guest');
}
public function register(Request $request)
{
$this->validator($request->all())->validate();
// dd($this->validator($request->all())->validate());
event(new Registered($user = $this->create($request->all())));
if (array_key_exists('type', $request->all())) {
return $this->registered($request, $user) ?: redirect('/buyersList/' . Auth::user()->id)->with('success', 'Registered successfully.');
} else {
return $this->registered($request, $user) ?: redirect($this->redirectPath())->with('success', 'Registered successfully. Please wait for the approval to access your account.');
}
}
protected function validator(array $data)
{
return Validator::make($data, [
'first_name' => ['required', 'string', 'max:255'],
'last_name' => ['required', 'string', 'max:255'],
'phone' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
*
* #return \App\User
*/
protected function create(array $data)
{
$user = User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'phone' => $data['phone'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
My data is not inserting to users table,and the create function is not working when I dd($user) it. How to make my code working. What my page shows when I try to submit data is :
Here is some really good baseline code that can be used if you simply want to store user input.
For example -
/**
* Handle an incoming registration request.
*
* #param \Illuminate\Http\Request $request
*
* #return \Illuminate\Http\RedirectResponse
*
* #throws \Illuminate\Validation\ValidationException
*/
public function store(Request $request)
{
$request->validate([
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => ['required', 'confirmed', Rules\Password::defaults()],
]);
$user = User::create([
'first_name' => $request->first_name,
'last_name' => $request->last_name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
event(new Registered($user));
Auth::login($user);
return redirect(RouteServiceProvider::HOME);
}
}
If you want to keep your validation out of your controller you can create a request to handle your validation.
Make a UserStoreRequest.php using Artisan command make:request. From there you can validate the request from the user to ensure they have all of the data you want.
Laravel has some good documentation on this as well. https://laravel.com/docs/8.x/validation

How to keep session after storing data in Laravel 8?

I'm new to Laravel. I have created custom Change Password in Laravel 8 using Livewire. But, after succeeded in updating the user password, my session is expired and redirected to login page. So, the question is how to keep the session alive and redirect to the current page?
Here's my code:
ChangeUserPassword.php
class ChangeUserPassword extends Component
{
public $oldPassword;
public $newPassword;
public $confirmPassword;
public function render()
{
return view('livewire.auth.change-user-password');
}
public function changePassword()
{
$this->validate([
'oldPassword' => 'required',
'newPassword' => ['required', Password::min(8)
->letters()
->mixedCase()
->numbers()
->symbols()
// ->uncompromised()
],
'confirmPassword' => 'required|min:8|same:newPassword'
]);
$user = User::find(auth()->user()->id);
if (Hash::check($this->oldPassword, $user->password)) {
$user->update([
'password' => Hash::make($this->newPassword),
'updated_at' => Carbon::now()->toDateTimeString()
]);
$this->emit('showAlert', [
'msg' => 'Your password has been successfully changed.'
]);
return redirect()->route('user.changepassword');
} else {
$this->emit('showAlertError', [
'msg' => 'Old password does not match.'
]);
}
}
}
change-user-password.blade.php
<div class="col-md-12">
<div class="card">
<div class="card-body">
<h4 class="card-title ml-2">Change Password</h4>
<form wire:submit.prevent="changePassword" role="form">
#csrf
<div class="row">
<div class="form-group col-md-4">
<label for="oldPassword" class="form-label">Old Password<span style="color: red"> *</span></label>
<input class="form-control #error('oldPassword') is-invalid #enderror" wire:model="oldPassword" name="oldPassword" id="oldPassword" type="password" />
#error('oldPassword')
<small id="helpId" class="text-danger">{{ $message }}</small>
#enderror
</div>
<div class="form-group col-md-4">
<label for="newPassword" class="form-label">New Password<span style="color: red"> *</span></label>
<input class="form-control #error('newPassword') is-invalid #enderror" wire:model="newPassword" name="newPassword" id="newPassword" type="password" />
#error('newPassword')
<small id="helpId" class="text-danger">{{ $message }}</small>
#enderror
</div>
<div class="form-group col-md-4">
<label for="confirmPassword" class="form-label">Confirm Password<span style="color: red"> *</span></label>
<input class="form-control #error('confirmPassword') is-invalid #enderror" wire:model="confirmPassword" name="confirmPassword" id="confirmPassword" type="password" />
#error('confirmPassword')
<small id="helpId" class="text-danger">{{ $message }}</small>
#enderror
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary pull-right"
wire:loading.attr="disabled">Save</button>
{{-- <div wire:loading>
<img style="width: 25px;" src="{{ asset('assets/images/spinner-small.gif') }}" alt="Loading">
</div> --}}
</div>
</div>
</form>
</div>
</div>
</div>
<script>
document.addEventListener('livewire:load', function (e) {
e.preventDefault()
})
</script>
Any suggestion would really help. Thanks.
Authenticate the user again after updating the password
if (Hash::check($this->oldPassword, $user->password)) {
$user->update([
'password' => Hash::make($this->newPassword),
'updated_at' => Carbon::now()->toDateTimeString()
]);
$this->emit('showAlert', [
'msg' => 'Your password has been successfully changed.'
]);
if(Auth::attempt(['email'=>$user->email, 'password'=>$this->newPassword])){
$request->session()->regenerate();
return redirect()->intended('user.changepassword');
}
} else {
$this->emit('showAlertError', [
'msg' => 'Old password does not match.'
]);
}

How to update profile with current image when an image file is not chosen in the edit form? I am using Laravel 8

Whenever I try to only save profile changes for the profile description and url in the edit form, I get an error because I didn't choose an image file also.
I would like to be able to update a profile with current image when an image file is not chosen in the edit form.
The error I keep getting is:
Call to a member function store() on null
...that error is referring to this line in the update method of my UserController:
$imagePath = request('image')->store('uploads', 'public');
This is the entire update method in my UserController:
public function update(User $user, Request $request)
{
$data = request()->validate([
'description' => 'nullable',
'url' => 'nullable',
'image' => 'nullable',
]);
$imagePath = request('image')->store('uploads', 'public');
auth()->user()->profile()->update([
'description' => $data['description'],
'url' => $data['url'],
'image' => $imagePath,
]);
return redirect('/users/' . auth()->user()->id);
}
Finally, this is the form in my edit-profile.blade.php file:
#section('content')
<body class="home_body">
<div class="home_container_div">
<div class="home_container">
<div class="home_box_div">
<form action="{{('/users/' . auth()->user()->id)}}" enctype="multipart/form-data" method="post">
#csrf
#method('PATCH')
<div class="form-group">
<label for="description" class="edit_description_label">Description</label>
<div class="edit_description_div">
<input id="description"
type="text"
class="form-control #error('description') is-invalid #enderror"
name="description"
value="{{ old('description' ) ?? auth()->user()->profile->description }}"
autocomplete="description" autofocus>
#error('description')
<div class="invalid-feedback-div">
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
</div>
#enderror
</div>
</div>
<div class="form-group">
<label for="url" class="edit_title_label">URL</label>
<div class="edit_url_div">
<input id="url"
type="text"
class="form-control #error('url') is-invalid #enderror"
name="url"
value="{{ old('url' ) ?? auth()->user()->profile->url }}"
autocomplete="url" autofocus>
#error('url')
<div class="invalid-feedback-div">
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
</div>
#enderror
</div>
</div>
<div class="create_post_image_div">
<label for="image" class="create_image_label">Profile Image</label>
<input type="file" class="form-control-file" id="image" name="image">
#error('image')
<div class="invalid-feedback-div">
<strong>{{ $message }}</strong>
</div>
#enderror
<div class="create_post_btn_div">
<button class="create_post_btn">Save Profile</button>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
#endsection
How can I resolve this issue?
You can skip the image upload part if the user has not selected any image file, like this:
public function update(User $user, Request $request)
{
$data = request()->validate([
'description' => 'required',
'url' => 'required',
'image' => 'nullable',
]);
$updateData = [
'description' => $data['description'],
'url' => $data['url'],
];
if (request('image')) {
$imagePath = request('image')->store('uploads', 'public');
$updateData['image'] = $imagePath;
}
auth()->user()->profile()->update($updateData);
return redirect('/users/' . auth()->user()->id);
}

Image Upload save file name on database using Laravel 5.4

please help me to create a image upload system using Laravel 5.4 and also can save the filename at the database...
i can't find any related article about this and i also tried a youtube tutorial but it doesn't explain how filename transferred on the database, hope you can help mo on this
thank you...
here so far my code that i done...
$this->validate(request(), [
'article_banner' => 'required | mimes:jpeg,jpg,png | max:2000',
'article_title' => 'required|max:255',
'article_date' => 'required|date',
'article_content' => 'required',
]
);
$article_banner = $request->file('article_banner');
$article_title = $request->input('article_title');
$article_date = $request->input('article_date');
$article_content = $request->input('article_content');
return $article_banner;
}
also here's my error on validation every time i upload a docx... not image
here's the article_add.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">User Management -> Edit User</div>
<div class="panel-body">
<form class="form-horizontal" role="form" method="POST" action="{{ route('article_add.post') }}" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('article_banner') ? ' has-error' : '' }}">
<label for="article_banner" class="col-md-4 control-label">Article Banner: </label>
<div class="col-md-6">
<input id="article_banner" type="file" class="form-control" name="article_banner" required autofocus>
<p class="help-block">Example block-level help text here.</p>
#if ($errors->has('article_banner'))
<span class="help-block">
<strong>{{ $errors->first('article_banner') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('article_title') ? ' has-error' : '' }}">
<label for="article_title" class="col-md-4 control-label">Article Title: </label>
<div class="col-md-6">
<input id="article_title" type="text" class="form-control" name="article_title" value="{{ old('article_title') }}" required autofocus>
#if ($errors->has('article_title'))
<span class="help-block">
<strong>{{ $errors->first('article_title') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('article_date') ? ' has-error' : '' }}">
<label for="article_date" class="col-md-4 control-label">Article Date: </label>
<div class="col-md-6">
<input id="article_date datepicker" type="text" class="form-control datepicker" name="article_date" value="{{ old('article_date') }}" data-provide="datepicker" required autofocus>
#if ($errors->has('article_date'))
<span class="help-block">
<strong>{{ $errors->first('article_date') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('article_content') ? ' has-error' : '' }}">
<div style="padding:10px;">
<label for="article_content">Article Date: </label>
<br />
<textarea id="content article_content" type="text" class="form-control" name="article_content" autofocus>{{ old('article_content') }}</textarea>
</div>
#if ($errors->has('article_content'))
<span class="help-block">
<strong>{{ $errors->first('article_content') }}</strong>
</span>
#endif
</div>
#if(session()->has('message'))
<div class="alert alert-success">
{{ session()->get('message') }}
</div>
#endif
#if(session()->has('errors'))
<div class="alert alert-danger">
{{ session()->get('errors') }}
</div>
#endif
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Submit
</button>
<a href="{{ url('article_management') }}" class="btn btn-primary">
Back
</a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
make one function as
public function uploadFiles($_destination_path, $images, $new_file_name) { //code to uplaod multiple fiels to path and return paths array wit file names
$file_name = str_replace(' ', '-', $new_file_name);
$paths = array('path' => $_destination_path . '/' . basename(Storage::disk($this->diskStorage)->putFileAs($_destination_path, $images, $file_name)),
'name' => pathinfo($file_name));
return $paths;
}
And pass required argument to it like as
$image = $request->file('image');
$fileName = $image->getClientOriginalName();
$destinationPath = '/images';
$img_path[] = $this->uploadFiles($destinationPath, $image, $fileName);
You will get required data in the img_path[] array variable.
public function feedbackPost(Request $request, $id)
{
$fileName1 = "";
$fileName2 = "";
$rules = array(
'conferencename' =>'required',
'yourname' =>'required',
'email' =>'required',
'objective' =>'required',
'results' =>'required',
'recommendations' =>'required',
'key_customers' =>'required',
'actions' =>'required',
'business_opportunities' =>'required',
'other_opportunities' =>'required',
'upload_leads' =>'mimes:csv,xls,xlsx',
'upload_attendees' =>'mimes:csv,xls,xlsx',
);
$validator = Validator::make($request->all(), $rules);
if ($validator->fails())
{
return back()->with('danger', 'File format not valid');
}
else
{
if($file=$request->hasFile('upload_attendees')) {
$file=$request->file('upload_attendees');
$fileName1=$file->getClientOriginalName();
if (!file_exists('uploads/feedback/attendees/'.$id.'')) {
mkdir('uploads/feedback/attendees/'.$id.'', 0777, true);
}
$destinationPath='uploads/feedback/attendees/'.$id.'';
$file->move($destinationPath,$fileName1);
}
if($file=$request->hasFile('upload_leads')) {
$file=$request->file('upload_leads');
$fileName2=$file->getClientOriginalName();
if (!file_exists('uploads/feedback/leads/'.$id.'')) {
mkdir('uploads/feedback/leads/'.$id.'', 0777, true);
}
$destinationPath='uploads/feedback/leads/'.$id.'';
$file->move($destinationPath,$fileName2);
}
$feedback = Feedback::insert([
'user_id' => $request->user_id,
'conferenceid' => $request->conferenceid,
'conferencename' =>$request->conferencename,
'yourname' =>$request->yourname,
'email' =>$request->email,
'objective' =>$request->objective,
'results' =>$request->results,
'recommendations' =>$request->recommendations,
'key_customers' =>$request->key_customers,
'actions' =>$request->actions,
'business_opportunities' =>$request->business_opportunities,
'other_opportunities' =>$request->other_opportunities,
'upload_attendees' =>$fileName1,
'upload_leads' =>$fileName2,
]);
}
return back()->with('success', 'Thanks! Your Feedback has been Submitted!');
}
This is how I did. You may try this.

Categories