Uploading file to database from input - php

I am learning Laravel and got stuck with one issue. I have created form with validation and all goes to database. Except my image_url with type="file"
<form method="POST" action="{{route('photos.store')}}" class="form-horizontal" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="">
#component('components.back', ['url' => route('photos.index')])
#endcomponent
<hr>
</div>
<div class="form-all">
<ul class="form-section page-section">
<li class="form-line" data-type="control_image" id="id_1">
<div id="cid_1" class="form-input-wide">
<div style="text-align:center;">
<img alt="" class="form-image" style="border:0px;" src="" height="42px" width="42px" data-component="image">
</div>
</div>
</li>
<li class="form-line" data-type="control_text" id="id_12">
<div id="cid_12" class="form-input-wide">
<div id="text_12" class="form-html" data-component="text">
<p><span style="color:#363636;font-size:xx-large;">Įkelti nuotrauką</span></p>
</div>
</div>
</li>
<li class="form-group{{ $errors->has('title')?' has-error' : ''}}" id="id_7">
<label class="form-label form-label-top" id="label_7" for="title">Pavadinimas</label>
<div id="cid_7" class="form-input-wide">
<input id="title" type="text" name="title" value="{{ old('title') }}" class="form-control" placeholder="Pavadinimas">
#if ($errors->has('title'))
<span class="help-block">
<strong>
{{ $errors->first('title')}}
</strong>
</span>
#endif </div>
</li>
<li class="form-group{{ $errors->has('description')?
' has-error' : ''}}">
<label class="form-label form-label-top" id="label_5" for="description">Aprašymas</label>
<div id="cid_5" class="form-input-wide">
<input id="description" type="text" name="description" value="{{ old('description') }}" class="form-control" placeholder = "Aprašymas">
#if ($errors->has('description'))
<span class="help-block">
<strong>
{{ $errors->first('description')}}
</strong>
</span>
#endif
</div>
</li>
<li class="form-group {{ $errors->has('image_url')?
' has-error' : ''}}">
<label class="form-label form-label-top" id="label_11" for="image_url">Nuotrauka</label>
<div id="cid_11" class="form-input-wide">
<input id="image_url" type="file" name="image_url" value="{{ old('image_url') }}" class="form-control">
#if ($errors->has('image_url'))
<span class="help-block">
<strong>
{{ $errors->first('image_url')}}
</strong>
</span>
#endif
</div>
</li>
<li class="form-group {{ $errors->has('category_id') ? 'has-error': ''}}">
<label class="form-label form-label-top" id="label_11">Kategorija</label>
#if(isset($photo))
<select name="category_id" class="form-control">
<option value="">Pasirinkti kategoriją</option>
#foreach($categories as $category)
<option value="{{$category->id}}">{{$category->title}}</option>
#endforeach
</select>
#else
<select name="category_id" class="form-control">
<option value="">Pasirinkti kategoriją</option>
#foreach($categories as $category)
<option value="{{$category->id}}">{{$category->title}}</option>
#endforeach
</select>
#endif
#if($errors->has('category_id'))
<span class="help-block">
<strong>{{ $errors->first('category_id')}}</strong>
</span>
#endif
</li>
<li class="form-line" data-type="control_button" id="id_2">
<div id="cid_2" class="form-input-wide">
<div style="text-align:center;" class="form-buttons-wrapper">
<button id="input_2" type="submit" class="form-submit-button" data-component="button">
Patvirtinti
</button>
</div>
</div>
</li>
</ul>
</div>
and my Controller looks like this:
public function create()
{
$categories = Category::all();
return view('photo.create', compact('photo','categories'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required|min:3',
'image_url'=> 'required',
'category_id' => 'required',
]);
$photo = new Photo;
$photo->title = $request->input('title');
$photo->image_url = $request->input('image_url');
$photo->description = $request->input('description');
$photo->category_id = $request->input('category_id');
$photo->save();
$request->session()->flash('create', $request->title. "Sekmingai sukurta");
$path = $request->image_url->store('images');
return redirect()->route('photos.index');
}
and seeder:
public function __construct( Photo $photo, Category $category) {
$this->photo = $photo;
$this->category = $category;
}
public function run()
{
$categories_ids = $this->category->pluck('id');
DB::table('photos')->insert(
[
'title' => '',
'image_url' => '',
'description' => '',
'category_id' => $categories_ids->random()
]);
}
I understand that I should put some if into Controller telling "If its not text, but file- accept file". But I am not able to find answer online.
Thank you for your advises in advance.

You will get image name from $fileName = $request->image_url->store('images');
and note $fileName wil return folder name also images/2Q3J1gU3j8NkMgt5HtGurSDtu5BIbeATNZb13Ih3.jpeg
$photo = new Photo;
if ($request->hasFile('image_url')) {
$fileName = $request->image_url->store('images');
$photo->image_url = $fileName;
}
$photo->title = $request->input('title');
$photo->description = $request->input('description');
$photo->category_id = $request->input('category_id');
$photo->save();
$request->session()->flash('create', $request->title. "Sekmingai sukurta");
return redirect()->route('photos.index');

Related

Laravel Controller Not Passing through Data

I am creating a very simple survey web app and in the answering of a created survey the controller is not functioning in the controller instead of dumping the array data and its information it instead redirects straight back to the form, and doesn't dump anything, there are no errors when executing the code it just redirects back to the form. I have tried remigrating, and rewriting the form in the view that fixed some things but still not the main issue
Survey Controller:
public function store(Questionnaire $questionnaire, $slug){
$data = request()->validate([
'responses.*.answerid' => 'required',
'responses.*.question_id' => 'required',
'survey.name' => 'required',
'survey.email' =>'required | email',
]);
dd($data);
}
Blade.php View:
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<h1>{{ $questionnaire->title }}</h1>
<form action = "/surveys/{{ $questionnaire->id }}-{{Str::slug($questionnaire->title)}}" method = "post">
#csrf
#foreach($questionnaire->questions as $key => $question)
<div class="card mt-4">
<div class="card-header"><strong> {{ $key + 1 }} </strong>{{ $question->question }}</div>
<div class = "card-body">
#error('responses.' . $key . '.answerid')
<small class = "text-danger">{{ $message }}</small>
#enderror
<ul class = "list-group">
#foreach($question->answers as $answer)
<label for="answer{{$answer->id}}">
<li class="list-group-item">
<input type = "hidden" name = 'responses[{{$key}}][questionid]' value = '{{$question->id}}'>
<input type = "radio" name = 'responses[{{$key}}][answerid]' id = 'answer{{ $answer->id }}' class = "mr-2" value= "{{$answer->id}}" {{ old('responses.' . $key . '.answer_id') == $answer->id ? 'checked' : '' }}>
{{ $answer->answer }}
</li>
</label>
#endforeach
</ul>
</div>
</div>
#endforeach
<div class="card mt-4">
<div class="card-header">Your Information</div>
<div class="card-body">
<div class="form-group">
<label for="name">Your Name</label>
<input name = "survey[name]" type="text" class="form-control" id="name" aria-describedby="nameHelp" placeholder="Enter Name">
<small id="nameHelp" class="form-text text-muted">Please Enter Your Name</small>
#error('name')
<small class = "text-danger">{{ $message }}</small>
#enderror
</div>
</div>
<div class="card-body">
<div class="form-group">
<label for="email">Your Email</label>
<input name = "survey[email]" type="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter Email">
<small id="emailHelp" class="form-text text-muted">Please enter your Email</small>
#error('email')
<small class = "text-danger">{{ $message }}</small>
#enderror
</div>
</div>
<div>
<button class = "btn btn-dark" type="submit">Complete Survey</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
#endsection
Routes file:
Route::get('/surveys/{questionnaire}-{slug}', 'SurveyController#show');
Route::post('/surveys/{questionnaire}-{slug}', 'SurveyController#store');
Questionnaire Model:
protected $guarded = [];
public function surveys(){
return $this->hasMany(Survey::class);
}
Survey Model:
protected $guarded = [];
public function questionnaire(){
return $this->belongsTo(Questionnaire::class);
}
public function responses(){
return $this->hasMany(SurveyResponse::class);
}
SurveyResponses Model:
protected $guarded = [];
public function survey(){
return $this->belongsTo(Survey::class);
}
Survey Migration:
Schema::create('surveys', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('questionnaire_id');
$table->string('name');
$table->string('email');
$table->timestamps();
});
Survey Responses Migration:
Schema::create('survey_responses', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('survey_id');
$table->unsignedBigInteger('questionid');
$table->unsignedBigInteger('answerid');
$table->timestamps();
});
This is the form in the blade.php file:
<form action = "/surveys/{{ $questionnaire->id }}-{{Str::slug($questionnaire->title)}}" method = "post">
#csrf
#foreach($questionnaire->questions as $key => $question)
<div class="card mt-4">
<div class="card-header"><strong> {{ $key + 1 }} </strong>{{ $question->question }}</div>
<div class = "card-body">
#error('responses.' . $key . '.answerid')
<small class = "text-danger">{{ $message }}</small>
#enderror
<ul class = "list-group">
#foreach($question->answers as $answer)
<label for="answer{{$answer->id}}">
<li class="list-group-item">
<input type = "hidden" name = 'responses[{{$key}}][questionid]' value = '{{ $question->id }}'>
<input type = "radio" name = 'responses[{{$key}}][answerid]' id = 'answer{{ $answer->id }}' class = "mr-2" value= "{{$answer->id}}" {{ old('responses.' . $key . '.answer_id') == $answer->id ? 'checked' : '' }}>
{{ $answer->answer }}
</li>
</label>
#endforeach
</ul>
</div>
</div>
#endforeach
<div class="card mt-4">
<div class="card-header">Your Information</div>
<div class="card-body">
<div class="form-group">
<label for="name">Your Name</label>
<input name = "survey[name]" type="text" class="form-control" id="name" aria-describedby="nameHelp" placeholder="Enter Name">
<small id="nameHelp" class="form-text text-muted">Please Enter Your Name</small>
#error('name')
<small class = "text-danger">{{ $message }}</small>
#enderror
</div>
</div>
<div class="card-body">
<div class="form-group">
<label for="email">Your Email</label>
<input name = "survey[email]" type="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter Email">
<small id="emailHelp" class="form-text text-muted">Please enter your Email</small>
#error('email')
<small class = "text-danger">{{ $message }}</small>
#enderror
</div>
</div>
<div>
<button class = "btn btn-dark" type="submit">Complete Survey</button>
</div>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
</div>
</div>
</form>
This is the input where the question id should be passed through:
<input type = "hidden" name = 'responses[{{$key}}][questionid]' value = '{{ $question->id }}'>
Your dd($data); in your controller not run if your request validate fails because when validation fails it redirect to your view with errors. So you have two way to see error:
1- use below code in your controller:
use Illuminate\Support\Facades\Validator; // Important to use Validator Facade in this case
public function store(Questionnaire $questionnaire, $slug){
$validator = Validator::make($request->all(), [
'responses.*.answerid' => 'required',
'responses.*.question_id' => 'required',
'survey.name' => 'required',
'survey.email' =>'required|email',
]);
if ($validator->fails()) {
//dd($validator);
return redirect(route('route-name'))
->withErrors($validator)
->withInput();
}
}
2- use below code in your view:
<!-- /resources/views/view-name.blade.php -->
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif

How I upload an image on laravel 6?

im trying to edit an image on laravel 6, but but it does not advance to next view, stays on the form view.
I have seen many tutorials of laravel 5.8 and 6. I can't make it work in any way
This is de controller:
public function update(Request $request, $id)
{
$validator = $request->validate([
'titulo' => 'required | max:50', //campo obligatorio y máximo 50 caracteres
'contenido' => 'required | max:150',
'imagen' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:4096',
]);
$image_name = time().'.'.$request->imagen->getClientOriginalExtension();
$request->image->move(public_path('images'), $image_name);
$datos = array(
'titulo' => $request->titulo,
'contenido' => $request->contenido,
'imagen' => $image_name,
);
Noticia::whereId($id)->update($datos);
return redirect('/mostrar');
}
THis is Web.php file:
Route::get('/actualizar/{id}', 'crearNoticiaController#update')->name('actualizar');
Route::get('/editar/{id}', 'crearNoticiaController#edit')->name('editar');
this is form file:
<div class="subir-imagen">
<form method="get" action="{{ route('actualizar', $noticia->id) }}" enctype="multipart/form-data">
#csrf
<div class="crear-titulo">
<input class="titulo" type="text" name="titulo" placeholder="Escriba el titulo" value="{{$noticia->titulo}}">
</div>
<div class="crear-contenido">
<textarea class="ckeditor" name="contenido" placeholder="Escriba el contenido" >
{{$noticia->contenido}}
</textarea>
</div>
<table border="2">
<tr>
<td><img src="{{URL::to('/')}}/images/{{$noticia->imagen}}" alt="imagen" width="250" align="left"/></td>
</tr>
</table>
<div class="form-group">
<div class="col-md-6">
<input type="file" class="form-control" name="imagen" />
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<input type="submit" class="btn btn-primary" value="Enviar" id="btn-enviar" />
</div>
</div>
</form>
</div>
Thnaks for help
I faced same issue, but luckily i solved this problem.I added my solution below, i think this will help you to solve this problem
public function updatePost(Request $request, $id)
{
$validatedData = $request->validate([
'title' => 'required|unique:posts|max:25|min:4',
'image' => 'mimes:jpeg,jpg,png,JPEG,JPG,PNG | max:100000',
]);
$data = array();
$data['category_id'] = $request->category_id;
$data['title'] = $request->title;
$data['details'] = $request->details;
$image = $request->file('image');
if($image)
{
$image_name = hexdec(uniqid());
$ext = strtolower($image->getClientOriginalExtension());
$image_full_name = $image_name.'.'.$ext;
$upload_path = 'public/assets/img/';
$image_url = $upload_path.$image_full_name;
$success = $image->move($upload_path,$image_full_name);
$data['image'] = $image_url;
unlink($request->old_photo);
$posts = DB::table('posts')->where('posts.id', $id)->update($data);
if($posts)
{
return Redirect()->route('all.posts')->with('success','Posts are inserted successfully');
}
else
{
return back()->with('error', 'Posts are not inserted successfully');
}
}
else
{
$data['image'] = $request->old_photo;
$posts = DB::table('posts')->where('posts.id', $id)->update($data);
if($posts)
{
return Redirect()->route('all.posts')->with('success','Posts are inserted successfully');
}
else
{
return back()->with('error', 'Posts are not inserted successfully');
}
}
}
edit_post.blade.php
#extends('welcome')
#section('content')
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
<p>
List Posts
</p>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="{{ url('posts.update_posts/'.$posts->id) }}" method="post" enctype="multipart/form-data">
#csrf
<div class="control-group">
<div class="form-group floating-label-form-group controls">
<div>Category Name</div>
<label>Category ID</label>
<select class="form-control" name="category_id">
#foreach($category as $categories)
<option value="{{ $categories->id }}" <?php if ($categories->id == $posts->category_id)
echo "selected"; ?> > {{ $categories->name }} </option>
#endforeach
</select>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls">
<label>Product Title</label>
<input type="text" name="title" class="form-control" value="{{ $posts->title }}" id="title" required data-validation-required-message="Please product name.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls">
<label>Details</label>
<textarea name="details" rows="5" class="form-control" value="{{ $posts->details }}" id="details"></textarea>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls">
<label>Product Image</label>
<input type="file" name="image" class="form-control" id="image"><br/>
Old Image : <img src="{{ URL::to($posts->image) }}" style="hight: 40px; width: 100px">
<input type="hidden" name="old_photo" value="{{ $posts->image }}">
</div>
</div>
<br>
<div id="success"></div>
<div class="form-group">
<button type="submit" class="btn btn-success" id="sendMessageButton">Update</button>
</div>
</form>
</div>
</div>
</div>
#endsection
First run on your project console command:
php artisan storage:link
Then try this code and if return any error message tell me khow:
$imagen = $request->file("imagen");
$extension = $imagen->extension();
$filename = time().".".$extension;
$request->file('imagen')->storeAs("public/images", $filename);
Finally check your public/images folder for image file exists.
Also you can read about storing uploaded files in laravel 6.x official documentation
I've solved with this way:
In web.php I put patch instead get
Route::patch('/actualizar/{id}', 'crearNoticiaController#update')->name('actualizar');
In the edit blade I put: #method('PATCH')
And this is the update in the controller:
public function update(Request $request, $id)
{
$noticia = Noticia::findOrFail($id);
$noticia->titulo = $request->get('titulo');
$noticia->contenido = $request->get('contenido');
$noticia->imagen = $request->file('imagen');
$validator = $request->validate([
'imagen' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:4096',
]);
$imageName = time().'.'.request()->imagen->getClientOriginalExtension();
request()->imagen->move(public_path('images'), $imageName);
$noticia->imagen = $imageName;
$noticia->update();
return redirect('/mostrar'); //Redirigimos a la la vista para mostrar las noticias
}

Why did not update table columns values in Laravel 5.6?

in laravel 5.6 app I have table name as vehicles, then I need update some of table values in VehicleController update function as this,
public function update(Request $request, $id)
{
$vehicle = Vehicle::find($id);
$vehicle->provincename = $request->input('provincename');
$vehicle->districtname = $request->input('districtname');
$vehicle->townname = $request->input('townname');
$vehicle->brandname = $request->input('brandname');
$vehicle->modelname = $request->input('modelname');
$vehicle->modelyear = $request->input('year');
$vehicle->condition = $request->input('condition');
$vehicle->milage = $request->input('milage');
$vehicle->detail = $request->input('data');
$vehicle->price = $request->input('price');
$vehicle->telephone = $request->input('telephone');
$vehicle->categoryname = $request->input('categoryname');
$vehicle->transmission = $request->input('transmission');
$vehicle->fueltype = $request->input('fueltype');
$vehicle->enginecapacity = $request->input('enginecapacity');
$vehicle->user_id = Auth::user()->id;
$vehicle->save();
and edit form action is,
<form method="post" action="{{ route('vehicles.edit', [$vehicles->id]) }}" enctype="multipart/form-data">
and update route is,
Route::post('myads/{id}', [
'uses' => '\App\Http\Controllers\VehicleController#update',
])->name('vehicles.edit');
and controller edit function,
public function edit($id)
{
$vehicles = Vehicle::findOrFail($id);
}
and edit route is,
Route::get('myads/{id}/edit', [
'uses' => '\App\Http\Controllers\VehicleController#edit',
'as'=> 'vehicles.edit'
]);
but when I click update button it did not update values. no any error occurred here only redirect back to edit form. how can fix this problem?
vehicle model
class Vehicle extends Model
{
use Searchable;
protected $guarded = [];
public function searchableAs()
{
return 'categoryname';
}
public function category()
{
return $this->belongsTo(Category::class);
}
public function uploads()
{
return $this->hasMany(Upload::class);
}
public function cars()
{
return $this->hasMany(Car::class);
}
public function vans()
{
return $this->hasMany(Car::class);
}
public function scopePersonal($query)
{
return $query->where('user_id', Auth::user()->id);
}
}
edit form is,
<form method="post" action="{{ route('vehicles.edit', [$vehicles->id]) }}" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-group{{ $errors->has('provincename') ? ' has-error' : '' }}">
<label for="exampleFormControlSelect1">Province</label>
<select name="provincename" id="provincename" class="form-control input dynamic" data-dependent="districtname" >
<option value="{{$vehicles->provincename}}">{!! $vehicles->provincename !!}</option>
#foreach($town_list as $town)
<option value="{{$town->provincename}}">{{$town->provincename}}</option>
#endforeach
</select>
#if ($errors->has('provincename'))
<span class="help-block">{{ $errors->first('provincename') }}</span>
#endif
</div>
<div class="form-group{{ $errors->has('districtname') ? ' has-error' : '' }}">
<label for="exampleFormControlSelect1">District</label>
<select name="districtname" id="districtname" class="form-control input dynamic" data-dependent="townname" >
<option value="{{$vehicles->districtname}}">{!! $vehicles->districtname !!}</option>
</select>
#if ($errors->has('districtname'))
<span class="help-block">{{ $errors->first('districtname') }}</span>
#endif
</div>
<div class="form-group{{ $errors->has('townname') ? ' has-error' : '' }}">
<label for="exampleFormControlSelect1">Town</label>
<select name="townname" id="townname" class="form-control input">
<option value="{{$vehicles->townname}}">{!! $vehicles->townname !!}</option>
</select>
#if ($errors->has('townname'))
<span class="help-block">{{ $errors->first('townname') }}</span>
#endif
</div>
<!--hidden select box-->
<div class="form-group" style="display: none;">
<label for="exampleFormControlSelect1">Vehicle Category</label>
<select name="categoryname" id="categoryname" class="form-control input dynamic" data-dependent="brandname" >
#foreach($model_list as $model)
<option value="{{$vehicles->categoryname}}">{{$vehicles->categoryname}}</option>
#endforeach
</select>
</div>
<div class="form-group{{ $errors->has('brandname') ? ' has-error' : '' }}">
<label for="exampleFormControlSelect1">Brand</label>
<select name="brandname" id="brandname" class="form-control input dynamic" data-dependent="modelname" >
<option value="{{$vehicles->brandname}}">{!! $vehicles->brandname !!}</option>
</select>
#if ($errors->has('brandname'))
<span class="help-block">{{ $errors->first('brandname') }}</span>
#endif
</div>
<div class="form-group{{ $errors->has('modelname') ? ' has-error' : '' }}">
<label for="exampleFormControlSelect1">Model</label>
<select name="modelname" id="modelname" class="form-control input">
<option value="{{$vehicles->modelname}}">{!! $vehicles->modelname !!}</option>
</select>
#if ($errors->has('modelname'))
<span class="help-block">{{ $errors->first('modelname') }}</span>
#endif
</div>
<div class="form-group{{ $errors->has('year') ? ' has-error' : '' }}">
<label for="formGroupExampleInput">Model Year</label>
<input type="text" class="form-control" id="year" placeholder="Year" name="year" value="{!! $vehicles->modelyear ?: '' !!}">
#if ($errors->has('year'))
<span class="help-block">{{ $errors->first('year') }}</span>
#endif
</div>
<div class="form-group{{ $errors->has('condition') ? ' has-error' : '' }}">
<label for="formGroupExampleInput">Condition</label>
<label class="radio-inline"><input type="radio" name="condition" value="used" #if($vehicles->condition == 'used') checked #endif>Used</label>
<label class="radio-inline"><input type="radio" name="condition" value="recondition" #if($vehicles->condition == 'recondition') checked #endif>Recondition</label>
<label class="radio-inline"><input type="radio" name="condition" value="new" #if($vehicles->condition == 'new') checked #endif> New</label>
#if ($errors->has('condition'))
<span class="help-block">{{ $errors->first('condition') }}</span>
#endif
</div>
<div class="form-group{{ $errors->has('milage') ? ' has-error' : '' }}">
<label for="formGroupExampleInput">Milage</label>
<input type="text" class="form-control" id="milage" placeholder="Milage" name="milage" value="{!! $vehicles->milage ?: '' !!}">
#if ($errors->has('milage'))
<span class="help-block">{{ $errors->first('milage') }}</span>
#endif
</div>
<div class="form-group{{ $errors->has('transmission') ? ' has-error' : '' }}">
<label for="exampleFormControlSelect1">Transmission</label>
<select class="form-control" id="transmission" name="transmission">
<option value="{!! $vehicles->transmission !!}">{!! $vehicles->transmission !!}</option>
<option value="Manual">Manual</option>
<option value="Auto">Auto</option>
<option value="Hybrid">Hybrid</option>
<option value="Electric">Electric</option>
<option value="Codak">codak</option>
</select>
#if ($errors->has('transmission'))
<span class="help-block">{{ $errors->first('transmission') }}</span>
#endif
</div>
<div class="form-group{{ $errors->has('fueltype') ? ' has-error' : '' }}">
<label for="exampleFormControlSelect1">Fuel Type</label>
<select class="form-control" id="fueltype" name="fueltype">
<option value="{!! $vehicles->fueltype !!}">{!! $vehicles->fueltype !!}</option>
<option value="Petrol">Petrol</option>
<option value="Diesel">Diesel</option>
<option value="Hybrid">Hybrid</option>
<option value="Electric">Electric</option>
</select>
#if ($errors->has('fueltype'))
<span class="help-block">{{ $errors->first('fueltype') }}</span>
#endif
</div>
<div class="form-group{{ $errors->has('enginecapacity') ? ' has-error' : '' }}">
<label for="formGroupExampleInput">Engine capacity</label>
<input type="text" class="form-control" id="enginecapacity" placeholder="Engine capacity" name="enginecapacity" value="{!! $vehicles->enginecapacity ?: '' !!}" >
#if ($errors->has('enginecapacity'))
<span class="help-block">{{ $errors->first('enginecapacity') }}</span>
#endif
</div>
<div class="form-group{{ $errors->has('data') ? ' has-error' : '' }}">
<label for="comment">More Details</label>
<textarea class="form-control" rows="5" id="data" name="data" rows="10" cols="10">{!! trim($vehicles->detail) !!}</textarea>
#if ($errors->has('data'))
<span class="help-block">{{ $errors->first('data') }}</span>
#endif
</div >
<div class="form-group{{ $errors->has('price') ? ' has-error' : '' }}">
<label for="formGroupExampleInput">Price</label>
<input type="text" class="form-control" id="price" placeholder="Price" name="price" value="{!! $vehicles->price ?: '' !!}">
#if ($errors->has('price'))
<span class="help-block">{{ $errors->first('price') }}</span>
#endif
</div>
<div class="form-group{{ $errors->has('telephone') ? ' has-error' : '' }}">
<label for="formGroupExampleInput">Telephone</label>
<input type="text" class="form-control" id="telephone" placeholder="Telephone" name="telephone" value="{!! $vehicles->telephone ?: '' !!}" >
#if ($errors->has('telephone'))
<span class="help-block">{{ $errors->first('telephone') }}</span>
#endif
</div>
<!-- <button type="submit" class="btn btn-primary" style="margin-top:10px">Submit</button>
</div> -->
#if( $vehicles->uploads->count() > 0 )
#php
$upload = $vehicles->uploads->sortByDesc('id')->first();
#endphp
<!-- <img id="preview" src="/images/{{ $upload->resized_name }}"> -->
<!--edit/delete buttons-->
#foreach( $vehicles-> uploads as $upload)
<img id="preview"
src="{{asset((isset($upload) && $upload->resized_name!='')?'images/'.$upload->resized_name:'images/noimage.png')}}"
height="200px" width="200px"/>
<input class="form-control" style="display:none" name="files[]" type="file" id="files" name="_token" value="{{ csrf_token() }}" enctype="multipart/form-data">
<br/>
<!-- Add Image | -->
<!-- <a style="color: red" href="javascript:removeImage()">Delete</a>
<input type="hidden" style="display: none" value="0" name="remove" id="remove"> -->
Edit Image|
<a class="button is-outlined" href="/myads/{{$upload->id}}/delete" onclick="return confirm('Are you sure to want to delete this record?')" >Delete</a></td>
<hr>
#endforeach
#endif
<button type="submit" class="btn btn-primary" style="margin-top:10px">Submit</button>
</div>
There will be mutiple reasons
1. You are not passing the csrf token with form request.
2. There will be one or more input value missing and you have not show the error message in the validation.
3. Vehicle id not exist.
etc.
try this way
and remove or comment this lines below
//$vehicle->save();
$vehicle = array('provincename'=>$request->input('provincename'),
'districtname' => $request->input('districtname'),
'townname' => $request->input('townname'),
'brandname' => $request->input('brandname'),
'modelname' => $request->input('modelname'),
'modelyear' => $request->input('year'),
'condition' => $request->input('condition'),
'milage' => $request->input('milage'),
'detail' => $request->input('data'),
'price' => $request->input('price'),
'telephone' => $request->input('telephone'),
'categoryname' => $request->input('categoryname'),
'transmission' => $request->input('transmission'),
'fueltype' => $request->input('fueltype'),
'enginecapacity' => $request->input('enginecapacity'),
'user_id' => Auth::user()->id);
Vehicle::where('id', $id)->update($vehicle);
You can use array to update your record and also make sure to pass csrf token when submitting a data. Add user_id column to the array.
DB::table('vehicles')
->where('id', $vehicle)
->update(['provincename ' => $request->input('provincename'),
'districtname'=>$request->input('districtname'),
'townname' =>input('townname'), 'user_id'=>Auth::user()->id ]);

Laravel 5.5 Crud Routing

I am new to Laravel 5.5 and I am trying to create a CRUD. Right now I am experiencing a views error. I am not sure where I went wrong. If someone point me in the right direction it would be greatly appreciated.
I have tried a few different attempts at resolving this issue such as changing my routes to Uppercase L instead of lower case l for leads to have it follow the directory casing but no avail.
My error
Route [leads.create] not defined. (View: .../resources/views/leads/index.blade.php)
Error's source coming from my index.blade.php file
<div class="pull-right">
<div class="btn-group"> <a href="{{ route('leads.create') }}" class="btn btn-info" >Add New</a> </div>
</div>
My Tree
views
|-- leads
| |-- create.blade.php
| |-- edit.blade.php
| |-- index.blade.php
| `-- show.blade.php
My Web.php
// Leads
Route::resource('Leads','LeadsController');
Route::get('leads/index', function () { return view('Leads.index'); });
Route::get('leads/create', function () { return view('Leads.create'); });
My Controller
namespace App\Http\Controllers;
use App\Leads;
use Illuminate\Http\Request;
class LeadsController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$videos = Leads::orderBy('id','DESC')->paginate(5);
return view('leads.index',compact('leads'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('leads.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'first_name' => 'required',
'primary_phone' => 'required',
]);
Leads::create($request->all());
return redirect()->route('leads.index')
->with('success','Lead created successfully');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$leads = Leads::find($id);
return view('leads.show',compact('leads'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$leads = Leads::find($id);
return view('leads.edit',compact('leads'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'first_name' => 'required',
'primary_phone' => 'required',
]);
Leads::find($id)->update($request->all());
return redirect()->route('leads.index')
->with('success','Lead updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
Leads::find($id)->delete();
return redirect()->route('leads.index')
->with('success','Lead deleted successfully');
}
}
You could use url() to go to a url link.
<div class="pull-right">
<div class="btn-group"> <a href="{{ url('leads/create') }}" class="btn btn-info" >Add New</a> </div>
</div>
Or you could use named route
Route::get('leads/create', function () {
return view('Leads.create');
})->name('leads.create');
Create Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Contact;
use Hash;
class ContactController extends Controller
{
public function index(Request $request)
{
$search = $request->get('search');
$field = $request->get('field') != '' ? $request->get('field') : 'first_name';
$sort = $request->get('sort') != '' ? $request->get('sort') : 'asc';
$contacts = new Contact();
$contacts = $contacts->where('first_name', 'like', '%' . $search . '%')
->orderBy($field, $sort)
->paginate(10)
->withPath('?search=' . $search . '&field=' . $field . '&sort=' . $sort);
return view('contacts.index', compact('contacts'))
->with('i', ($request->input('page', 1) - 1) * 10);
}
public function create()
{
return view('contacts.create');
}
public function store(Request $request)
{
$request->validate([
'first_name'=>'required|min:3|max:50',
'last_name'=>'required|min:3|max:50',
'email'=>'required|email|unique:contacts',
'phone' => 'required|numeric|phone',
'password' =>'required|min:3|max:20',
'confirm_password' =>'required|min:3|max:20|same:password'
]);
$contact = new Contact([
'first_name' => $request->get('first_name'),
'last_name' => $request->get('last_name'),
'email' => $request->get('email'),
'job_title' => $request->get('job_title'),
'city' => $request->get('city'),
'country' => $request->get('country'),
'phone' => $request->get('phone'),
'password' => $request->get('password')
]);
$contact->save();
return redirect('/contacts/index')->with('success', 'Contact saved!');
}
public function edit($id)
{
$contact = Contact::find($id);
//print_r($contact);exit;
return view('contacts.edit', compact('contact'));
}
public function update(Request $request, $id)
{
$request->validate([
'first_name'=>'required|min:3|max:50',
'last_name'=>'required|min:3|max:50',
'email'=>'required|email',
'city' => 'required'
]);
$contact = Contact::find($id);
$contact->first_name = $request->get('first_name');
$contact->last_name = $request->get('last_name');
$contact->email = $request->get('email');
$contact->job_title = $request->get('job_title');
$contact->city = $request->get('city');
$contact->country = $request->get('country');
$contact->phone = $request->get('phone');
$contact->password = $request->get('password');
$contact->save();
return redirect('/contacts/index')->with('success', 'Contact updated!');
}
public function delete($id)
{
$contact = Contact::find($id);
$contact->delete();
return redirect('/contacts/index')->with('success', 'Contact deleted!');
}
}
Create Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Contact extends Model
{
protected $fillable = [
'first_name',
'last_name',
'email',
'city',
'country',
'job_title',
'phone',
'password'
];
public function setPasswordAttribute($password)
{
$this->attributes['password'] = bcrypt($password);
}
}
Create routes in web.php
Route::get('contacts/index', 'ContactController#index');
Route::get('contacts/create', 'ContactController#create');
Route::post('contacts/store', 'ContactController#store');
Route::get('contacts/edit/{id}', 'ContactController#edit');
Route::post('contacts/update/{id}', 'ContactController#update');
Route::post('contacts/delete/{id}','ContactController#delete');
Route::post('contacts/index', 'ContactController#index');
create base.blade.php in resources/views folder
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Laravel 5.8 & MySQL CRUD Tutorial</title>
<link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
#yield('main')
</div>
<script src="{{ asset('js/app.js') }}" type="text/js"></script>
</body>
</html>
Create index.blade.php in contacts folder
#extends('base')
#section('main')
<div class="col-sm-12">
#if(session()->get('success'))
<div class="alert alert-success">
{{ session()->get('success') }}
</div>
#endif
</div>
<div class="row">
<div class="col-sm-12">
<h1 class="display-3">Contacts</h1>
<a class="pull-right btn btn-primary" href="<?php echo url('contacts/create') ?>">Add Contacts</a>
</div>
</div>
<div class="row">
<form action="<?php echo url('contacts/index')?>" method="post">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<button class="pull-right btn btn-primary" href="<?php echo url('contacts/index') ?>">view all</button>
<div class="pull-right col-lg-3 input-group custom-search-form">
<input class="form-control" name="search" placeholder="Search..." type="text" value="{{ request('search') }}">
<span class="input-group-btn ">
<button class="btn btn-default" type="submit">
<i class="fa fa-search"></i>
</button>
</span>
</div>
<input type="hidden" value="{{request('field')}}" name="field"/>
<input type="hidden" value="{{request('sort')}}" name="sort"/>
<table class="table table-striped">
<thead>
<tr>
<td>ID</td>
<td>
<a href="{{url('contacts/index')}}?search={{request('search')}}&field=first_name&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
Name
</a>
{{request('field','first_name')=='first_name'?(request('sort','asc')=='asc'?'▴':'▾'):''}}
</td>
<td>
<a href="{{url('contacts/index')}}?search={{request('search')}}&field=email&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
Email
</a>
{{request('field','email')=='email'?(request('sort','asc')=='asc'?'▴':'▾'):''}}
</td>
<td>
<a href="{{url('contacts/index')}}?search={{request('search')}}&field=job_title&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
Job Title
</a>
{{request('field','job_title')=='job_title'?(request('sort','asc')=='asc'?'▴':'▾'):''}}
</td>
<td>
<a href="{{url('contacts/index')}}?search={{request('search')}}&field=city&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
City
</a>
{{request('field','city')=='city'?(request('sort','asc')=='asc'?'▴':'▾'):''}}
</td>
<td>
<a href="{{url('contacts/index')}}?search={{request('search')}}&field=country&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
Country
</a>
{{request('field','country')=='country'?(request('sort','asc')=='asc'?'▴':'▾'):''}}
</td>
<td colspan = 2>Actions</td>
</tr>
</thead>
<tbody>
#foreach($contacts as $contact)
<tr>
<td>{{$contact->id}}</td>
<td>{{$contact->first_name}} {{$contact->last_name}}</td>
<td>{{$contact->email}}</td>
<td>{{$contact->job_title}}</td>
<td>{{$contact->city}}</td>
<td>{{$contact->country}}</td>
<td>
Edit
</td>
<td>
<form action="delete/<?php echo $contact->id?>" method="post">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<button class="btn btn-danger" type="submit">Delete</button>
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
</form>
</div>
#endsection
Create form create.blade.php
#extends('base')
#section('main')
<div class="row">
<div class="col-sm-8 offset-sm-2">
<h1 class="display-3">Add a contact</h1>
<div>
<form method="post" action="{{ url('contacts/store') }}">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="first_name">First Name:</label>
<input type="text" class="form-control" name="first_name"/>
<span class="text-danger">{{ $errors->first('first_name') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="last_name">Last Name:</label>
<input type="text" class="form-control" name="last_name"/>
<span class="text-danger">{{ $errors->first('last_name') }}</span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" name="email"/>
<span class="text-danger">{{ $errors->first('email') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="phone">Phone:</label>
<input type="text" class="form-control" name="phone"/>
<span class="text-danger">{{ $errors->first('phone') }}</span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="city">City:</label>
<input type="text" class="form-control" name="city"/>
<span class="text-danger">{{ $errors->first('city') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="country">Country:</label>
<input type="text" class="form-control" name="country"/>
<span class="text-danger">{{ $errors->first('country') }}</span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control" name="password"/>
<span class="text-danger">{{ $errors->first('password') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="confirm_password">Confrim Password:</label>
<input type="password" class="form-control" name="confirm_password"/>
<span class="text-danger">{{ $errors->first('confirm_password') }}</span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="job_title">Job Title:</label>
<input type="text" class="form-control" name="job_title"/>
<span class="text-danger">{{ $errors->first('job_title') }}</span>
</div>
</div>
</div>
<button type="submit" class="btn btn-primary">Add contact</button>
</form>
</div>
</div>
</div>
#endsection
Create edit.blade.php
#extends('base')
#section('main')
<div class="row">
<div class="col-sm-8 offset-sm-2">
<h1 class="display-3">Update a contact</h1>
<form method="post" action="{{ url('contacts/update', $contact->id) }}">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="first_name">First Name:</label>
<input type="text" class="form-control" name="first_name" value="<?php echo $contact->first_name ?>" />
<span class="text-danger">{{ $errors->first('first_name') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="last_name">Last Name:</label>
<input type="text" class="form-control" name="last_name" value="<?php echo $contact->last_name ?>" />
<span class="text-danger">{{ $errors->first('last_name') }}</span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" name="email" value="<?php echo $contact->email ?>" />
<span class="text-danger">{{ $errors->first('email') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="phone">Phone:</label>
<input type="text" class="form-control" name="phone" value="<?php echo $contact->phone ?>" />
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="city">City:</label>
<input type="text" class="form-control" name="city" value="<?php echo $contact->city ?>" />
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="country">Country:</label>
<input type="text" class="form-control" name="country" value="<?php echo $contact->country ?>" />
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="job_title">Job Title:</label>
<input type="text" class="form-control" name="job_title" value='<?php echo $contact->job_title;?>' />
</div>
</div>
</div>
<button type="submit" class="btn btn-primary">Update</button>
</form>
</div>
</div>
#endsection
Phone number validation put this code in AppServiceProvider.php in boot function
Validator::extend('phone', function($attribute, $value, $parameters, $validator) {
return substr($value, 0, 3) == '+91';
});
Link for Crud Operation - https://www.techiediaries.com/php-laravel-crud-mysql-tutorial/

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