how to upload optional documents - laravel

I need to upload few files optional. here I add code
<form action="{{ route('UserConfirmation', app()->getLocale()) }}" enctype="multipart/form-data" method="post">
<div class="form-group form-control">{{ csrf_field() }}
<input type="tel" name="ContactNo" value="{{ old('ContactNo') }}" required>
<input class="form-control" type="file" name="nic" required><br>
<input class="form-control" type="file" name="BillingProof" ><br>
<input class="form-control" type="file" name="CashSlip" ><br>
<input class="btn btn-primary" type="submit" name="submit" ><br>
</div>
</form>
here is two required fields, and others are not require,so I need those save in database as empty, here i add my current controller.
public function store(Request $request)
{
//dd($request);
$validator = Validator::make($request->all(), [
'ContactNo' => ['required', 'string','max:15'],
]);
if ($validator->fails()) {
return redirect()->back() ->withErrors($validator)->withInput();
}
$nicPath = $request->file('nic')->store('public');
$billPath = $request->file('BillingProof')->store('public');
$CashSlipPath = $request->file('CashSlip')->store('public');
$UC = $request->all();
$UserCon= new UserConfirm();
$UserCon->ContactNo = $UC['ContactNo'];
$UserCon->NIC = str_replace('public/', '', $nicPath );
$UserCon->BillingProof = str_replace('public/', '', $billPath );
$UserCon->CashSlip = str_replace('public/', '', $CashSlipPath );
$UserCon->Status = "none";
$UserCon->Remark = "none";
$UserCon->save();
Session::flash('UserConfirm','We recived your Documents and we are working on it');
return redirect()->route('feedback',app()->getLocale());
}
and also I add nullable attribute to table fields. here i attach image of table

You should check if the file has been sent at first:
$billPath = $request->hasFile('BillingProof') ? $request->file('BillingProof')->store('public') : null;
$CashSlipPath = $request->hasFile('CashSlip') ? $request->file('CashSlip')->store('public') : null;
and then save it into your storage.

Related

Get product id to store attachments accordingly

I currently have the add attachment button for each product on the product list page. After clicking the button, will proceed to add attachment form. How do I get the current product ID from the product table in order to store the attachment data into the attachment table?
Route
Route::post('/store/{product}', 'AttachmentController#store')->name('attachment.store');
Product Model
public function attachment()
{
return $this->hasMany(Attachment::class, 'product_id', 'id');
}
Attachment Model
public function product()
{
return $this->belongsTo(Product::class, 'product_id');
}
Controller
public function create()
{
return view('document.create', ['prod' => Product::select('id', 'name')->get()]);
}
public function store(Request $request, Product $product) {
$data['product_id'] = $product->id;
$data = $request->validate([
'file' => 'required',
'file.*' => 'mimes:csv,xlsx,pdf,docx',
]);
$attachmentData = [];
if($request->hasFile('file'))
{
foreach($request->file('file') as $file) {
$path = public_path('storage/attachments/'.$request->product_id);
$fileName = time().'-'.$file->getClientOriginalName();
$file->move($path, $fileName);
$attachmentData[] = $fileName;
}
$data['file'] = json_encode($attachmentData);
}
$attachment = Attachment::create($data);
return redirect()->route('product.index')->with('success','Attachment added successfully');
}
Blade View
<form method="POST" action="{{route('attachment.store')}}" enctype="multipart/form-data">
#csrf
<h3><b>Add Attachment</b></h3>
<input type="submit" class="btn btn-primary mr-2" value="Save">
<div class="row">
<h4 class="card-title">General</h4>
<input type="text" name="product_id" value="{{ $product->id ?? '' }}" hidden>
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" class="form-control" name="name" required>
</div>
<div class="form-group">
<label>Attachment </label>
<div class="input-group-append">
<label for="attachment" class="btn btn-info">Upload</label>
<input id="attachment" type="file" name="file[]" multiple required>
</div>
</div>
</div>
</form>
You have to use form action like below
<form method="POST" action="{{route('attachment.store',['product'=>$product->id])}}" enctype="multipart/form-data">

Laravel - search submit is not redirecting to the next blade

In my Laravel-5.8, I am using the index as the search page:
public function index()
{
$search = '';
if (request('search'))
{
$search = request('search');
return redirect()->route('client', [$search]);
}
return view('index', ['search' => $search]);
}
public function client($clientid)
{
$myparam = $clientid;
$client = new Client();
$res = $client->request('GET','https://example/{$myparam}', [
'query' => ['key' => 'jkkffd091']
])->getBody();
$geoLocation = json_decode($res->getContents(), true);
return view('client', [
'geoLocation' => $geoLocation
]);
}
Here is my index blade:
<form method="GET" action="{{ route('index', ['search' => $search]) }}">
<div class="field">
<label class="label blog-sidebar-label" for="search">
<input class="search-field" type="search" name="search" id="search" placeholder="client id..." value="{{ $search }}">
</label>
</div>
</form>
I have this route:
Route::get('/', [HomeController::class, 'index'])->name('index');
Route::get('client/{search}', [HomeController::class, 'client'])->name('client');
What I want to achieve is that when the search button for index is submitted with the clientid in the text input field, it should take the clientid as parameter and pass it to client controller. Also redirect to client blade.Then when nothing is in the text input field, it should indicate.
But it is not redirecting. How do I achieve this?
Thanks
Probably you want to submit without a submit button. Then you can submit with JS :
<form id="submitForm" method="GET" action="{{ route('index', ['search' => $search]) }}">
<div class="field">
<label class="label blog-sidebar-label" for="search">
<input class="search-field" type="search" name="search" id="search" placeholder="client id..." value="{{ $search }}">
</label>
</div>
</form>
<!-- JS code below -->
<script>
document.getElementById("search").onchange = function() {myFunction()};
function myFunction() {
document.getElementById("submitForm").submit();
}
</script>

Call to a member function getClientOriginalName() on array

I have a multiple image. When I upload multiple image. I get this error.
Call to a member function getClientOriginalName() on array
my blade
<form action="{{ route('design-studios.store') }}" method="post" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" id="title" name="title" value="{{ old('title') }}">
</div>
//......
<div class="form-group">
<fieldset class="border p-3">
<legend>Slideshow</legend>
<div class="form-group">
<label for="sliders">Image</label>
<input id="sliders" name="sliders[]" type="file" multiple class="form-control">
</div>
</fieldset>
</div>
</form>
My Controller.
public function store(Request $request)
{
$design_studio = new DesignStudio;
$design_studio->user_id = 1;
$design_studio->title = $request->title;
$design_studio->lang = $request->lang;
$design_studio->body = $request->body;
if($request->has('image')) {
$image = $request->file('image');
$filename = $image->getClientOriginalName();
$image->move(public_path('images/design-studio'), $filename);
$design_studio->image = $request->file('image')->getClientOriginalName();
}
if ($sliders = $request->file('sliders')) {
foreach ($sliders as $slider) {
$filename = $slider->getClientOriginalName();
$slider->move(public_path('images/design-studio'), $filename);
$design_studio->sliders = $request->file('sliders')->getClientOriginalName();
}
}
$design_studio->save();
$design_studio->categories()->attach($request->category);
return redirect()->route('design-studios.index');
}
My Model
protected $casts = [
'sliders' => array()
];
I get this error.
Call to a member function getClientOriginalName() on array
Here you need to call that method on the file you are looping through instead of trying to call it on the array of files.
$design_studio->sliders = $slider->getClientOriginalName();

How to edit image and update in laravel

I have a table called Services, now this table has the following -
-id
-title
-body
-image
-slug
-timestamps
And in administrator, services page I created for Add, Edit, Delete it.
My problem is edit and update a image. A strange problem is that, when I change the of image to aaaaa field in the service table (database), Nothing happens. should happen. because I changed rename of image to aaaaa.
web.php
Route::resource('services', 'ServiceController');
ServiceController.php
public function edit(Service $service)
{
return view('Admin.services.edit', compact('service'));
}
public function update(Request $request, Service $service)
{
$service->title = $request->title;
$service->body = $request->body;
if($request->has('image')) {
$image = $request->file('image');
$filename = $image->getClientOriginalName();
$image->move(public_path('images/services'), $filename);
$service->image = $request->file('image')->getClientOriginalName();
}
$service->update();
return redirect()->route('services.index');
}
edit.blade.php
<form class="form-horizontal" action="{{ route('services.update', $service->id) }}" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
{{ method_field('PATCH') }}
#include('Admin.layouts.errors')
<div class="form-group">
<label for="title">عنوان</label>
<input type="text" class="form-control" id="title" name="title" placeholder="عنوان" value="{{ $service->title ? : old('title') }}">
</div>
<div class="form-group">
<label for="body">متن</label>
<textarea class="form-control" rows="10" id="body" name="body" placeholder="متن">{{ $service->body ? : old('body') }}</textarea>
</div>
<div class="form-group">
<label for="images">تصویر</label>
<div class="custom-file">
<input type="file" class="custom-file-input" id="images" name="images">
<label class="custom-file-label" for="images">تصویر محصول</label>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">ذخیره</button>
</div>
</form>
Service.php
protected $fillable = [
'title',
'body',
'image',
'slug',
];
I even changed the controller in the update method as follows, nothing happened.
$service->save();
I think one of efficient way to edit image in laravel.
add this at top of the controller
use File;
First of get your bannerId in a variable
$bannerId = $request->banner_id;
get object of that id by find ().
$bannerData = FrontEndBanner::find($bannerId);
check if file exist and check if file already exist then delete that file else same name will inserted in imageName variable
if ($request->hasFile('banner_image')){
$image_path = public_path("/uploads/resource/".$bannerData->banner_name);
if (File::exists($image_path)) {
File::delete($image_path);
}
$bannerImage = $request->file('banner_image');
$imgName = $bannerImage->getClientOriginalName();
$destinationPath = public_path('/uploads/resource/');
$bannerImage->move($destinationPath, $imgName);
} else {
$imgName = $bannerData->banner_name;
}
$bannerData->title = $request->banner_title;
$bannerData->banner_name = $imgName;
$bannerData->save();
If anyone have issue then comment
In the html you have:
<input type="file" class="custom-file-input" id="images" name="images">
and in Controller: $request->file('image').
Replace
<input type="file" class="custom-file-input" id="images" name="images">
with
<input type="file" class="custom-file-input" id="images" name="image">

How to Manage Accounts in the Laravel 5 FrameWork - MVC - with this code?

How to Manage Accounts in the Laravel 5 FrameWork - MVC - with this code? I got it all for a default presentation but i still get an Undefined Variable request with this code - please your answer will be appreciated:
UserController:
public function account(&$data, $request){
User::get_user(self::$data,$request);
self::$data['title'] = self::$data['title'] . 'Edit Account';
return view('forms.account', self::$data);
}
public function postAccount(AccountRequest $request){
User::edit_user($request);
return redirect('');
}
AccountRequest:
public function rules()
{
return [
'name' => 'required|min:2|max:70',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:6|max:10|confirmed',
];
}
Model:
static public function get_user(&$data,$request){
$sql = "SELECT * FROM users WHERE id = ". Session::get('user_id');
$data['users'] = DB::select($sql);
}
static public function edit_user(&$data,$request) {
$id = $data['id'];
$sql = "SELECT * FROM users WHERE id = ".$id;
$getVal = DB::select($sql);
if($data['name'] || $data['password'] || $data['email']){
if($data['name']){
DB::update("UPDATE users SET name = ? WHERE id = ?",[$data['name'],$id]);
session(['user_name' => $data['name']]);
}
if($data['password']){
DB::update("UPDATE users SET password = ? WHERE id = ?",[bcrypt($data['password']),$id]);
}
if($data['email']){
DB::update("UPDATE users SET email = ? WHERE id = ?",[$data['email'],$id]);
}
}
Session::flash('sm',$request['name'] . '`s Has Been Updated');
}
Web:
Route::get('user/account', 'UserController#account');
Route::post('user/account', 'UserController#postAccount');
HTML:
#extends('master')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-12 text-center">
<h1>Edit Your Account -</h1>
</div>
<div class="row" style="margin-left:30%;">
<div class="col-md-6">
<form action="" method="post">
{{ csrf_field() }}
<input type="hidden" name="user_id" value="{{ $user['id'] }}">
<div class="form-group">
<label for="name"></label>
<input value="{{ $user['name'] }}" type="text" name="name"
class="form-control" id="name" placeholder="Name">
</div>
<div class="form-group">
<label for="email"></label>
<input value="{{ $user['email'] }}" type="text" name="email"
class="form-control" id="email" placeholder="Email">
</div>
<div class="form-group">
<label for="editpassword"></label>
<input type="password" name="password" class="form-control"
id="editpassword" placeholder="Edit Password">
</div>
<div class="form-group">
<label for="editpasswordconf"></label>
<input type="password" name="password_confirmation" class="form-
control" id="editpasswordconf" placeholder="Confirm New Password">
</div>
<div class="form-group text-center">
<input type="submit" name="submit" value="Update Details" class="btn
btn-primary">
</div>
</form>
</div>
</div>
</div>
#endsection
Your AccountController should look like this:
public function edit($request, Account $account){
return view('forms.account', [
'account' => $account,
'title' => 'Edit Account'
]);
}
public function update(AccountRequest $request, Account $account){
$account->update($request->all());
Session::flash('sm', $account->name . ' Has Been Updated');
return redirect()->back();
}
AccountRequest:
public function rules()
{
return [
'name' => 'required|min:2|max:70',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:6|max:10|confirmed',
];
}
That is about as much code as you need for this process... please read the documentation for Eloquent https://laravel.com/docs/5.4/eloquent

Resources