How to store an image inside the database using laravel? [duplicate] - php

This question already has answers here:
laravel 5.4 upload image
(12 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 2 years ago.
I am stuck trying to store an image of a product in the database. My database is currently just storing the name of the image, like chicken.jpeg. Not really a chicken by the way hahaha. So the current output is the filename of the image is stored in the database. However the desired result should be the whole image is stored in the database, that way after the image is uploaded through the form, there would be no need for the user to keep the image on their computer anymore. I have some code below if you feel interested to help me.
This is my ProductController#store:
public function store(Request $request)
{
$data = request()->validate([
'productName' => 'required',
'productImage' => 'required',
'productLink' => 'required',
'productPrice' => 'required',
'productDescription' => 'required',
]);
$product = new Product([
'productName' => $request->get('productName'),
'productImage' => $request->get('productImage'),
'productLink' => $request->get('productLink'),
'productPrice' => $request->get('productPrice'),
'productDescription' => $request->get('productDescription'),
]);
$product->save();
return redirect('/pr');
}
This is my form:
<form action="/storeProduct" method="post">
#csrf
<label for="productName">Product Name:</label><br>
<input type="text" id="productName" name="productName" autocomplete="off" value="{{
old('productName') }}"><br>
#error('productName') <p style="color: red">{{ $message }}</p> #enderror
<label for="productImage">Product Image:</label><br>
<input type="file" id="productImage" name="productImage" autocomplete="off" value="{{
old('productImage') }}"><br>
#error('productImage') <p style="color: red">{{ $message }}</p> #enderror
<label for="productLink">Product Link:</label><br>
<input type="text" id="productLink" name="productLink" autocomplete="off" value="{{
old('productLink') }}"><br>
#error('productLink') <p style="color: red">{{ $message }}</p> #enderror
<label for="productPrice">Product Price:</label><br>
<input type="decimal" id="productPrice" name="productPrice" autocomplete="off" value="{{
old('productPrice') }}"><br>
#error('productPrice') <p style="color: red">{{ $message }}</p> #enderror
<label for="productDescription">Product Description:</label><br>
<input type="text" id="productDescription" name="productDescription" autocomplete="off" value="
{{ old('productDescription') }}"><br>
#error('productDescription') <p style="color: red">{{ $message }}</p> #enderror
<input type="submit" value="Submit">
</form>
Thanks for taking the time to read my question and attempting to help me. I have attached my GitHub repository below, if you are interested in reading through my code.
https://github.com/xiaoheixi/blog

For uploading image through form you need to set enctype in your form first
and also instead of uploading an image into database you should upload it to your public image folder it will be far better and store only name of image into your database
changes in form:
<form enctype='multipart/form-data' action="/storeProduct" method="post">
#csrf
<label for="productName">Product Name:</label><br>
<input type="text" id="productName" name="productName" autocomplete="off" value="{{
old('productName') }}"><br>
#error('productName') <p style="color: red">{{ $message }}</p> #enderror
<label for="productImage">Product Image:</label><br>
<input type="file" id="productImage" name="productImage" autocomplete="off" value="{{
old('productImage') }}"><br>
#error('productImage') <p style="color: red">{{ $message }}</p> #enderror
<label for="productLink">Product Link:</label><br>
<input type="text" id="productLink" name="productLink" autocomplete="off" value="{{
old('productLink') }}"><br>
#error('productLink') <p style="color: red">{{ $message }}</p> #enderror
<label for="productPrice">Product Price:</label><br>
<input type="decimal" id="productPrice" name="productPrice" autocomplete="off" value="{{
old('productPrice') }}"><br>
#error('productPrice') <p style="color: red">{{ $message }}</p> #enderror
<label for="productDescription">Product Description:</label><br>
<input type="text" id="productDescription" name="productDescription" autocomplete="off" value="
{{ old('productDescription') }}"><br>
#error('productDescription') <p style="color: red">{{ $message }}</p> #enderror
<input type="submit" value="Submit">
</form>
and for uploading an image you can use
if ($request->hasFile('productImage')) {
$image = $request->file('productImage');
$name = time().'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/images');
$image->move($destinationPath, $name);
}
for file upload reference read this answer Laravel Image upload

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'],
];

What is the cause of the "route not defined" error in this Laravel 8 application?

I am working on a Laravel application that requires user registration and login.
Alter registration, a user should have the possibility to add more info to his/her profile.
For this purpose, I did the following:
In routes/web.php I have the necessary routes, including update:
Auth::routes();
Route::get('/dashboard', [App\Http\Controllers\Dashboard\DashboardController::class, 'index'])->name('dashboard');
Route::get('/dashboard/profile', [App\Http\Controllers\Dashboard\UserProfileController::class, 'index'])->name('profile');
Route::post('/dashboard/profile/update', [App\Http\Controllers\Dashboard\UserProfileController::class, 'update'])->name('update');
In the newly created Controllers\Dashboard\UserProfileController.php I have:
namespace App\Http\Controllers\Dashboard;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Auth;
use App\Models\UserProfile;
class UserProfileController extends Controller
{
public function index(UserProfile $user)
{
return view('dashboard.userprofile',
array('current_user' => Auth::user())
);
}
public function update(Request $request, $id)
{
$id = Auth::user()->id;
$request->validate([
'first_name' => ['required', 'string', 'max:255'],
'last_name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
]);
$current_user = User::find($id);
$current_user->first_name = $request->get('first_name');
$current_user->last_name = $request->get('last_name');
$current_user->email = $request->get('email');
$current_user->bio = $request->get('bio');
$current_user->avatar = $request->get('avatar');
$current_user->update();
return redirect('/dashboard/profile')->with('success', 'User data updated successfully');
}
}
In the view file that holds the form (resources\views\dashboard\userprofile.blade.php) I have:
<form action="{{ route('dashboard/profile/update') }}" enctype='multipart/form-data' method="post" novalidate>
{{csrf_field()}}
<div class="form-group">
<input type="text" id="first_name" name="first_name" placeholder="First name" class="form-control" value="{{$current_user->first_name}}">
#if ($errors->has('first_name'))
<span class="errormsg text-danger">{{ $errors->first('first_name') }}</span>
#endif
</div>
<div class="form-group">
<input type="text" id="last_name" name="last_name" placeholder="Last name" class="form-control" value="{{$current_user->last_name}}">
#if ($errors->has('first_name'))
<span class="errormsg text-danger">{{ $errors->first('last_name') }}</span>
#endif
</div>
<div class="form-group">
<input type="text" id="email" name="email" placeholder="E-mail address" class="form-control" value="{{$current_user->email}}">
#if ($errors->has('email'))
<span class="errormsg text-danger">{{ $errors->first('email') }}</span>
#endif
</div>
<div class="form-group">
<textarea name="bio" id="bio" class="form-control" cols="30" rows="6">{{$current_user->bio}}</textarea>
#if ($errors->has('bio'))
<span class="errormsg text-danger">{{ $errors->first('bio') }}</span>
#endif
</div>
<label for="avatar" class="text-muted">Upload avatar</label>
<div class="form-group d-flex">
<div class="w-75 pr-1">
<input type='file' name='avatar' id="avatar" class="form-control border-0 py-0 pl-0 file-upload-btn">
#if ($errors->has('file'))
<span class="errormsg text-danger">{{ $errors->first('avatar') }}</span>
#endif
</div>
<div class="w-25">
<img class="rounded-circle img-thumbnail avatar-preview" src="{{asset('images/avatars/default.png')}}" alt="{{$current_user->first_name}} {{$current_user->first_name}}">
</div>
</div>
<div class="form-group mb-0">
<input type="submit" name="submit" value='Save' class='btn btn-block btn-primary'>
</div>
</form>
The problem:
For a reason I was unable to figure out, whenever I am on the dashboard/profile route (in the browser), Laravel throws this error:
Route [dashboard/profile/update] not defined. (View: Path\to\views\dashboard\userprofile.blade.php)
What am I missing?
The route() function accepts a name, not a URL: https://laravel.com/docs/8.x/routing#generating-urls-to-named-routes
So you should have used route('update'). Though seeing your code, you might not realize the ->name() method should accept a unique route name. So you should make sure you don't have any other route named 'update'.
Some people do this: ->name('dashboard.profile.update'). You can see if you like this convention.
I applied an easy fix, thanks to the info received from the community:
I replaced <form action="{{ route('dashboard/profile/update') }}" enctype='multipart/form-data' method="post" novalidate> with:
<form action="{{ route('update') }}" enctype='multipart/form-data' method="post" novalidate>

Laravel: I can't upload my dropzone file into my database

Hi I am new to laravel and javascript,
I have a multiple input forms for updating of product information including a image upload using Dropzone.js to update product image. However I cant see to update my image file as I keep getting a null value for my dropzone image when I have already dragged a file in.
Below are my codes in the product-edit page:
<form action="{{ route('merchant.product.update', $product->prodID) }}" method="POST" class="dropzone" enctype="multipart/form-data">
{{ csrf_field() }}
{{ method_field('PATCH') }}
<div class="form-group">
<h5>Code</h5>
<input type="text" name="prodCode" class="form-control" id="prodCode" placeholder="Product Code" value="{{ old('prodCode', $product->prodCode) }}" required>
<div class="spacer"></div>
</div>
<div class="form-group">
<h5>Description</h5>
<textarea id="prodDesc" name="prodDesc" class="form-control" id="prodDesc" placeholder="Description" rows="5" required> {{ $product->prodDesc }}</textarea>
<div class="spacer"></div>
</div>
<div class="form-group">
<h5>Price</h5>
<input type="text" name="price" class="form-control" id="price" placeholder="Price" value="{{ old('price', $product->price)}}">
<div class="spacer"></div>
</div>
<div class="form-group">
<h5>Quantity</h5>
<input type="number" name="quantity" class="form-control" id="quantity" placeholder="Quantity" value="{{ old('quantity', $product->quantity)}}">
<div class="spacer"></div>
</div>
<div class="form-group">
<h5>Feature Product</h5>
<div class="switch">
<input type="checkbox" name="featured" class="switch-input" value="1" {{ old('featured', $product->featured=="true") ? 'checked="checked"' : '' }}/>
<div class="circle"></div>
</div>
</div>
<div class="form-group">
<h5>Product Image</h5>
<div id="dropzoneDragArea" class="dz-default dz-message dropzoneDragArea">
<span>Upload Image</span>
</div>
<div class="dropzone-previews"></div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-large btn-primary">Update Product</button>
</div>
<div class="spacer"></div>
</form>
Below are the Javascript portion of the blade.php:
Below are my Controller Methods I have for the update:
public function storeImage(Request $request) {
if($request->file('file')){
// Upload path
$destinationPath = 'img/products/';
// Get File
$image = $request->file('file');
// Get File Name
$imageName = $image->getClientOriginalName();
// Uploading File to given path
$image->move($destinationPath,$imageName);
$product = new Product();
$product->where('prodID', '=', $request->{'prodID'}, 'AND', 'created_by_merchant_id', '=', $this->checkMerchantID())
->update([
'prodImage' => $imageName,
]);
}
}
//update Product details
public function update(Request $request, $prodID)
{
if ($this->isCodeExist($request->{'prodCode'}, $request->{'prodID'})) {
return back()->withErrors('This code already exists!');
}
try{
$db = new Product();
$db->where('prodID', '=', $prodID, 'AND', 'created_by_merchant_id', '=', $this->checkMerchantID())
->update([
'prodCode' => $request->{'prodCode'},
'prodImage' =>$this->storeImage($request),
'prodDesc' => $request->{'prodDesc'},
'price' => $request->{'price'},
'quantity' => $request->{'quantity'},
'featured' => $request->input('featured') ? true : false,
]);
return back()->with('success_message', 'Product updated successfully!');
} catch (\Illuminate\Database\QueryException $ex) {
Log::channel('merchant_error')->error($ex);
return back()->withErrors('There seems to be an error in updating');
}
}

In Laravel ,how to validate all the input fields, display error messages if any, and return back to the form with the inputs if there are errors

I am trying to validate user registration form using Laravel Validator::make. The code works, including showing the error messages in the respective fields.
But my problems are :-
1) No matter what I type in the email field, it always produces an error. So, it does not redirects me to the next page, even if I type the correct format example#example.com . I tried removing the "email" validator and tried. It still shows me "email field is required" message
2) In addition to that,if there are any errors in one or more fields,the page gets redirected back but the input fields are not filled up with the past input .
Here is the Controller page
public function showdata(Request $request){
$first_name = $request->first_name;
$last_name = $request->last_name;
$email = $request->eid;
$password = $request->password;
$confirm_password = $request->confirm_password;
$mobno = $request->mobno;
$dob = $request->dob;
$gender = $request->gender;
$address = $request->address;
$country = $request->country;
$time = $request->dt;
$messages=
[
'required' => "The :attribute field is required",
'email.email' => "The :attribute :input format should be example#example.com/.in/.edu/.org....",
'email.unique' => "The :attribute :input is taken. Please use another email address",
'confirm_password.same' => "Password and Confirm password fields must match exactly",
'mobno.digits' => "The :attribute field accepts only numbers",
'mobno.digits:10' => "The :attribute should be 10 digits long",
'dob.date_format' => "The date format :input should be YYYY-MM-DD",
'address.string' => "The :attribute :input must be in the form of a string"
];
$rules = [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|min:8',
'confirm_password' => 'required|min:8|same:password',
'mobno' => 'required|digits:10',
'dob' => 'required|date|date_format:Y-m-d',
'gender' => 'required',
'address' => 'required|string',
'country' => 'required'
];
$validate = Validator::make($request->all(),$rules,$messages);
if($validate->fails()){
return back()->withInput()->withErrors($validate->messages());
}
else{
return view('recheck_form')
->with('first_name',$first_name)
->with('last_name',$last_name)
->with('email',$email)
->with('password',$password)
->with('mobno',$mobno)
->with('dob',$dob)
->with('gender',$gender)
->with('address',$address)
->with('country',$country)
->with('time',$time);
}
}
}
And the Blade Page
<div class="container pt-2">
<div class="row shadow p-3 mb-5 bg-info rounded text-center text-white">
<div class="col ">
<h2>New User Registration</h2>
</div>
</div>
</div>
<div class="row m-5 p-5 bg-light text-info">
<div class="col">
<form class="form-group" method="post" action="recheck-form" autocomplete="off">
<div class="form-group {{ $errors->has('first_name') ? ' has-error' : '' }}">
#csrf
<label for="fname">First Name:</label>
<input type="text" class="form-control" name="first_name">
<small class="text-danger">{{$errors->first('first_name') }}</small>
</div>
<div class="form-group {{ $errors->has('last_name') ? ' has-error' : '' }}">
<label for="lname">Last Name:</label>
<input type="text" class="form-control" name="last_name">
<small class="text-danger">{{ $errors->first('last_name') }}</small>
</div>
<div class="form-group {{ $errors->has('email') ? ' has-error' : '' }}">
<label for="eid">Email/Username:</label>
<input type="text" class="form-control" name="eid">
<small class="text-danger">{{ $errors->first('email') }}</small>
</div>
<div class="form-group {{ $errors->has('password') ? ' has-error' : '' }}">
<label for="pwd">Password:</label>
<input type="password" class="form-control" name="password">
<small class="text-danger">{{$errors->first('password') }}</small>
</div>
<div class="form-group {{ $errors->has('confirm_password') ? ' has-error' : '' }}">
<label for="confpwd">Confirm Password:</label>
<input type="password" class="form-control" name="confirm_password">
<small class="text-danger">{{ $errors->first('confirm_password') }}</small>
</div>
<div class="form-group {{ $errors->has('mobno') ? ' has-error' : '' }}">
<label for="mobno">Mobile Number:</label>
<input type="text" class="form-control" name="mobno">
<small class="text-danger">{{ $errors->first('mobno') }}</small>
</div>
<div class="form-group {{ $errors->has('dob') ? ' has-error' : '' }}">
<label for="dob">Date of Birth(in YYYY-MM-DD):</label>
<input type="text" class="form-control" name="dob">
<small class="text-danger">{{ $errors->first('dob') }}</small>
</div>
<div class="form-group {{ $errors->has('gender') ? ' has-error' : '' }}">
<label for="gender">Gender:</label>
<br>
<input class="form-check-input" type="radio" name="gender" id="Female" value="Female">
<label class="form-check-label" for="Female">
Female
</label>
<input class="form-check-input" type="radio" name="gender" id="Male" value="Male">
<label class="form-check-label" for="Male">
Male
</label>
<input class="form-check-input " type="radio" name="gender" id="Other" value="Other">
<label class="form-check-label" for="Other">
Other
</label>
<small class="text-danger">{{ $errors->first('gender') }}</small>
</div>
<div class="form-group {{ $errors->has('address') ? ' has-error' : '' }}">
<label for="address">Address:</label>
<textarea class="form-control" rows="5" name="address"></textarea>
<small class="text-danger">{{ $errors->first('address') }}</small>
</div>
<div class="form-group {{ $errors->has('country') ? ' has-error' : '' }}">
<label for="country">Country:</label>
<select name="country" class="form-control" id="countrylist">
<option value disabled selected>Select Country</option>
#foreach($countryname as $key => $country)
<option id="countryname" value="{{$country->countryname}}">{{$country->countryname}}</option>
#endforeach
</select>
<small class="text-danger">{{ $errors->first('country') }}</small>
</div>
<div class="form-group">
<label for="dt">Date and Time of Submission:</label>
<input type="text" class="form-control" name="dt" readonly value=#php date_default_timezone_set("Asia/Kolkata"); echo date("Y-m-d,H:i:s ") #endphp>
</div>
<div class="form-group text-center">
<input type="submit" class="btn btn-primary mb-2">
</div>
I dont know how to upload images to Stack Overflow questions. If you can tell me, I can show you the exact problem via images.
First of all, you are doing wrong in your code. In the validator rules and messages array, you did write wrong.
Please check the below code It will resolve your issue.
$messages=
[
'eid.required' => "The :attribute field is required",
'eid.email' => "The :attribute :input format should be example#example.com/.in/.edu/.org....",
'eid.unique' => "The :attribute :input is taken. Please use another email address",
'confirm_password.same' => "Password and Confirm password fields must match exactly",
'mobno.digits' => "The :attribute field accepts only numbers",
'mobno.digits:10' => "The :attribute should be 10 digits long",
'dob.date_format' => "The date format :input should be YYYY-MM-DD",
'address.string' => "The :attribute :input must be in the form of a string"
];
$rules = [
'first_name' => 'required',
'last_name' => 'required',
'eid' => 'required|email|unique:users',
'password' => 'required|min:8',
'confirm_password' => 'required|min:8|same:password',
'mobno' => 'required|digits:10',
'dob' => 'required|date|date_format:Y-m-d',
'gender' => 'required',
'address' => 'required|string',
'country' => 'required'
];
The page gets redirected back but the input fields are not filled up with the past input.
For this issue you can try the below approach will definitely work
$validate = Validator::make($request->all(),$rules,$messages);
if($validate->fails()){
return redirect()->back()->withErrors($validate->messages())->withInput();
}
And in your input value attribute please write like this value="{{ old('name') }}"
<input type="text" name="name" value="{{ old('name') }}" />
<input type="email" name="email" value="{{ old('email') }}" />
<input type="text" name="first_name" value="{{ old('first_name') }}" />
The names of your field and rules dont match. please update
"name="eid" to be name="email" as that's what the rule 'email' => 'required|email|unique:users' will look for.
Then also update $email = $request->email;
In order to reset the previously entered values after the error re-direct, please update your view like this:
In view:
<input type="text" class="form-control" name="email" value="{{ old('email') }}">
Note,
If you want to keep it as eid, thats fine too, you just need to make sure everything uses eid, ie:
<div class="form-group {{ $errors->has('eid') ? ' has-error' : '' }}">
<label for="eid">Email/Username:</label>
<input type="text" class="form-control" name="eid" value="{{ old('eid') }}">
<small class="text-danger">{{ $errors->first('eid') }}</small>
</div>
$email = $request->eid;
'eid.email' => "The :attribute :input format should be example#example.com/.in/.edu/.org....",
'eid.unique' => "The :attribute :input is taken. Please use another email address",
'eid' => 'required|email|unique:users',

Laravel - Upload mp3 file failed

I met a problem with upload of an mp3 file
Everytime I send the form I got a "File "" not found.
and that's what i got from my POST DATA :
IMAGE OF POST DATA
Here it's the controller :
public function Display()
{
return view('pages.new');
}
public function Post(Request $request)
{
$rules = [
'name' => ['required'],
'sources' => ['required'],
'cover' => ['required'],
'resume-podcast' => ['required'],
];
$validator = Validator::make($request->all(), $rules);
$pathimg = $request->file('cover')->store('/audio/cover');
$pathsources = $request->file('sources')->store('/audio/sources');
$podcasts = Audio::create(
[
'name' => request('name'),
'user_id' => auth()->id(),
'sources' => $pathsources,
'cover' => $pathimg,
'description' => request('resume'),
]);
return($pathsources);
flash("Yes !")->success();
}
Here it's the view :
<form action="/new" method="POST" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group" >
<label for="exampleInputPassword1">Nom podcast</label>
#if($errors->has('name'))
<p class="bg-warning"> {{ $errors->first('name') }}</p>
#endif
<input class="form-control" name="name" id="name" type="text" aria-describedby="emailHelp" placeholder="Nom du podcast">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Description du podcast</label>
#if($errors->has('resume-podcast'))
<p class="bg-warning"> {{ $errors->first('resume-podcast') }}</p>
#endif
<input class="form-control" name="resume-podcast" id="resume-podcast" type="text" aria-describedby="emailHelp" placeholder="Description rapide">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Source (url)</label>
#if($errors->has('sources'))
<p class="bg-warning"> {{ $errors->first('sources') }}</p>
#endif
<input class="form-control" id="sources" name="sources" type="file">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Cover (url)</label>
#if($errors->has('cover'))
<p class="bg-warning"> {{ $errors->first('cover') }}</p>
#endif
<input class="form-control" id="cover" name="cover" type="file>
</div>
<input type="submit" class="btn btn-primary btn-block" value="Ajouter podcast">
</form>
</div>
</div>
</div>
I saw it was a recurrent problem but didn't find any solution :(
I already try with mimes:audio/mpeg but nothing...
There are 4/5 reasons why you faced that issue.
1 - You're uploading a large file and didn't change the php.ini file to allow file sized more than a certain value. change the value of these variables.
post_max_size = 2G
or 500M
upload_max_filesize=500M
2 - You've changed the php.ini but didn't restart the server.
3 - You've messed up the route.
4 - Your HTML form isn't correct. You might be missing:
enctype="multipart/form-data"
Also,
<input type="file" name="pic" accept="audio/*">
5 - You didn't change
file_uploads = On
``` in php.ini file

Categories