Upload image file with specified name using laravel - ajax

I want to store the image file with the id as a name .
So I tried the following code :
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'casting_photo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if ($validator->passes()) {
$request->casting_photo->storeAs(public_path('castingimages'),$request->Casting()->id.'.'.$request->casting_photo->extension() );
$data = ['casting_photo' =>$request->casting_photo];
Casting::create($data);
return response()->json(["status" => "success", "message" => "Success! post created."]);
}
return response()->json(["status" => "failed", "message" => "Alert! post not created"]);
}
But it gives me the 500 (Internal Server Error)
EDIT
if ($validator->passes()) {
$input['casting_photo'] = $request->Casting()->id .'.'.$request->casting_photo->extension();
$request->casting_photo->storeAs(public_path('castingimages'),$request->Casting()->id.'.'.$request->casting_photo->extension() );
$data = ['casting_name' => $request->casting_name,
'casting_cin' => $request->casting_cin,
'casting_email' => $request->casting_email,
'casting_phone' => $request->casting_phone,
'casting_age' => $request->casting_age,
'casting_sexe' => $request->casting_sexe,
'casting_city' => $request->casting_city,
'casting_address' => $request->casting_address,
'casting_photo'=> $input['casting_photo'] ];
Casting::create($data);
return response()->json(["status" => "success", "message" => "Success! post created."]);
}
return response()->json(["status" => "failed", "message" => "Alert! post not created"]);
I tried that and the same error occurs.
EDIT2
$fileName = $request->get('id') . '.' . $request->file('casting_photo')->extension();
$request->file('casting_photo')->storeAs('castingimages', $fileName);
But in databse I finf the image stored with just the extension like .png
EDIT3
<form id="castingform" method="post" action="castings" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="hidden" name="id" />
<div class="form-group col-md-6">
<label for="casting_name">Nom</label>
<input type="text" class="form-control" id="casting_name" name="casting_name" placeholder="Nom" >
<span class="text-danger">{{ $errors->first('casting_name') }}</span>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">Upload</span>
</div>
<div class="custom-file">
<input type="file" name="casting_photo" class="custom-file-input" id="casting_photo">
<div class="input-group-prepend">
<span class="text-danger">{{ $errors->first('casting_photo') }}</span>
</div>
<label class="custom-file-label" for="casting_photo">Choose file</label>
</div>
</div>
<button type="submit" id="createBtn" class="btn btn-success">Sign in</button>
</form>

You are accessing unknown id from request
$input['casting_photo'] = $request->Casting()->id .'.'.$request->casting_photo->extension();
it should be
$request->casting_photo->storeAs(public_path('castingimages'),$request->id.'.'.$request->casting_photo->extension() );
Updated
$request->casting_photo->storeAs(public_path('castingimages'),$request->Casting()->id.'.'.$request->casting_photo->extension() );
$data = ['casting_name' => $request->casting_name,
'casting_cin' => $request->casting_cin,
'casting_email' => $request->casting_email,
'casting_phone' => $request->casting_phone,
'casting_age' => $request->casting_age,
'casting_sexe' => $request->casting_sexe,
'casting_city' => $request->casting_city,
'casting_address' => $request->casting_address,
$casting=Casting::create($data);
$casting->casting_photo=$casting->id.'.'.$request->casting_photo->extension() );
$casting->save();

Related

Can't upload files using livewire

I can't submit a form with file in order to proced to upload method, the file is selected when I submit it says that the file is required (empty data).
Everything works fine on mylocal Windows machine but I face the problem when using vps for production.
view :
<form wire:submit.prevent="submit" enctype="multipart/form-data">
<div>
#if(session()->has('message'))
<div class="alert alert-success">
{{ session('message') }}
</div>
#endif
</div>
<div class="form-group">
<label for="exampleInputName">Title:</label>
<input type="text" class="form-control" id="exampleInputName" placeholder="Enter title" wire:model="title">
#error('title') <span class="text-danger">{{ $message }}</span> #enderror
</div>
<div class="form-group">
<label for="exampleInputName">File:</label>
<input type="file" class="form-control" id="exampleInputName" wire:model="file">
#error('file') <span class="text-danger">{{ $message }}</span> #enderror
</div>
<button type="submit" class="btn btn-success">Save</button>
</form>
controller :
use WithFileUploads;
public $file, $title;
public function submit()
{
$validatedData = $this->validate([
'title' => 'required',
'file' => 'required',
]);
$validatedData['name'] = $this->file->store('files', 'public');
// File::create($validatedData);
session()->flash('message', 'File successfully Uploaded.');
}
VPS folders :
I tried to change permessions, user group.... no success.
try this
use WithFileUploads;
public $title;
public $file;
protected function rules()
{
return [
'title' => ['required', 'string', 'max:50'],
'file' => ['required', 'file', 'mimes:pdf,doc,docx', 'max:5000']
];
}
public function submit()
{
$this->validate();
$data = [
'title' => $this->title
];
if (!empty($this->file)) {
$url = $this->file->store('files', 'public');
$data['file'] = $url;
}
File::create($data);
session()->flash('message', 'File successfully Uploaded.');
}

How can I solve 404 errors in Laravel 7?

I'm making a registration form using Laravel 7, my form has a "preview" step where users first check the details and either submit the details as they are or edit. The actual submission of the details happens in the blade file named preview.blade.php and this is where I have placed the form action for posting the data. This part works well, the edit part is the one with the problem as it gives 404 error. Please help.
In my register.blade.php:
<form method="post" action="{{ url('/preview-details') }}" id="regForm">
{{ csrf_field() }}
<div class="form-group">
<label for="region">Your Region</label><span class="text-danger">*</span>
<input type="text" class="form-control" name="region" id="region" placeholder="e.g Westlands" required>
</div>
<label for="start_date">Date</label><span class="required">*</span>
<input type="date" class="form-control" id="start_date" name="start_date"
value="{{ old('start_date') }}" required>
<!--Other fields here-->
</form>
In my preview.blade.php:
<div>
<a href="{{route('edit_preview')}}">
<button type="button" class="btn btn-primary btn-sm"
style="float:right;"><i class="fas fa-edit"> </i>Edit</button>
</a>
</div>
<form method="post" action="{{ url('/client-registration') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="region">Your Region</label><span class="text-danger">*</span>
<input type="text" class="form-control" name="region" id="region" placeholder="e.g Westlands" required>
</div>
<label for="start_date">Date</label><span class="required">*</span>
<input type="date" class="form-control" id="start_date" name="start_date"
value="{{ old('start_date') }}" required>
<!--Other fields here-->
</form>
In my edit_preview.php (this one shows 404 error):
<form method="post" action="{{ url('/client-registration') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="region">Your Region</label><span class="text-danger">*</span>
<input type="text" class="form-control" name="region" id="region" placeholder="e.g Westlands" required>
</div>
<label for="start_date">Date</label><span class="required">*</span>
<input type="date" class="form-control" id="start_date" name="start_date"
value="{{ old('start_date') }}" required>
<!--Other fields here-->
</form>
In my Routes file:
Route::get('/client-registration', 'Auth\Client\RegisterController#create')->name('client-registration');
Route::post('/client-registration', 'Auth\Client\RegisterController#store');
Route::post('/preview-details', 'Auth\Client\PreviewRegisterDetailsController#confirmation')->name('preview-details');
Route::post('/preview-details-existing', 'Auth\Client\PreviewDetailsExistingClientController#confirmation')->name('preview-existing');
Route::post('/edit_preview', 'Auth\Client\EditRegisterDetailsController#editDetails')->name('edit_preview');
In my Preview Controller (It works well):
class PreviewRegisterDetailsController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
// Validating the User
public function confirmation(Request $request)
{
$categories = Category::all();
$request->validate([
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'telephone_number' => 'required|digits:10',
'email' => 'required|string|email|max:255|unique:users','regex:/^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,6}$/',
'password' => 'required|string|min:6|confirmed',
'password_confirmation' => 'required',
'region' => 'required|string',
'description' => 'required|string|max:2500',
'start_date' => 'required|date',
'client_region' => 'string|max:500',
'client_category' => 'integer|max:255',
]);
$data = $request->all();
return view('auth.client.preview', compact('categories', 'data'));
}
}
In my edit details controller:
class EditRegisterDetailsController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
// Validating the User
public function editDetails(Request $request)
{
$categories = Category::all();
$request->validate([
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'telephone_number' => 'required|digits:10',
'email' => 'required|string|email|max:255|unique:users','regex:/^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,6}$/',
'password' => 'required|string|min:6|confirmed',
'password_confirmation' => 'required',
'region' => 'required|string',
'description' => 'required|string|max:2500',
'start_date' => 'required|date',
'client_region' => 'string|max:500',
'client_category' => 'integer|max:255',
]);
$data = $request->all();
return view('auth.client.edit_preview', compact('categories', 'data'));
}
}

cannot update image when edit data on laravel

there is no problem when I do create new data. everything is ok including uploading image. My image inserted to public/image directory.
But when i try editing or updating, i have a problem. my image that should be inserted to public/image not work on update function.
the controller is below
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'sequence' => 'required',
'image' => 'required|image|max:2048',
'link' => 'required',
'status' => 'required',
]);
$image = $request->file('image');
$new_name = $request->name .rand(). '.' . $image->getClientOriginalExtension();
$image->move(public_path('images'), $new_name);
$form_data = array(
'name' => $request->name,
'sequence' => $request->sequence,
'image' => $new_name,
'link' => $request->link,
'status' => $request->status,
);
Banner::create($form_data);
return redirect()->route('banner.index');
}
public function update(Request $request, Banner $banner)
{
$image_name = $request->hidden_image;
$image = $request->file('image');
if($image != ''){
$request->validate([
'name' => 'required',
'sequence' => 'required',
'image' => 'image|max:2048',
'link' => 'required',
'status' => 'required',
]);
$image_name = $request->name .rand(). '.' . $image->getClientOriginalExtension();
$image->move(public_path('images'), $image_name);
}
else{
$request->validate([
'name' => 'required',
'sequence' => 'required',
'link' => 'required',
'status' => 'required',
]);
}
$form_data = array(
'name' => $request->name,
'sequence' => $request->sequence,
'image' => $image_name,
'link' => $request->link,
'status' => $request->status,
);
Banner::whereId($banner)->update($form_data);
return redirect()->route('banner.index');
}
And my view code is below
<form action="{{ route('banner.update',$banner->id) }}" method="POST">
#csrf
#method('PUT')
<div class="row" style="margin-top: 10px">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Name:</strong>
<input type="text" name="name" value="{{ $banner->name }}" class="form-control" placeholder="Name">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Sequence</strong>
<input type="number" name="sequence" value="{{ $banner->sequence }}" class="form-control" placeholder="Sequence">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Image</strong>
<div class="col-md-8">
<img src="{{ URL::to('/') }}/images/{{ $banner->image }}" class="img-thumbnail" width="200" />
</div>
<div class="col-md-8">
<input type="file" name="image" />
<input type="text" name="hidden_image" value="{{ $banner->image }}" />
</div>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Link</strong>
<input type="text" name="link" value="{{ $banner->link }}" class="form-control" placeholder="Link">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Status</strong>
<input type="text" name="status" value="{{ $banner->status }}" class="form-control" placeholder="Status">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
your form is missing enctype attribute and so no file is passing with the form. add that attribute and everything will work.
<form action="{{ route('banner.update',$banner->id) }}" method="POST" enctype="multipart/form-data">

How to fix "Undefined variable: img_name" error in laravel

i have a project on laravel 5.8; i have this error; please help me :
Undefined variable: img_name
this my html code :
<div class="input-group control-group increment" >
<input id="p_image" type="file" name="p_image" class="form-control">
<div class="input-group-btn">
<button class="btn btn-success" type="button"><i class="glyphicon glyphicon-plus"></i>Add</button>
</div>
</div>
<div class="clone hide">
<div class="control-group input-group" style="margin-top:10px">
<input id="p_image" type="file" name="p_image" class="form-control">
<div class="input-group-btn">
<button class="btn btn-danger" type="button"><i class="glyphicon glyphicon-remove"></i> Remove</button>
</div>
</div>
</div>
My Controller :
public function store(Request $request)
{
$this->validate(request(), [
'p_image' => 'image|mimes:jpg,jpeg,png|max:2048'
]);
if($request->hasFile('p_image')){
$img_name = time() . '.' . $request->p_image->getClientOriginalExtension();
}
// awi sora s lfolder public/uploads
if($request->hasFile('p_image')){
$request->p_image->move(public_path('upload'), $img_name);
}
Image::create([
'p_image' => $img_name,
'post_id' => $post->id
]);
return redirect('/posts');
}
I have this error, i dont understand, if you can explain me please; thank you
Undefined variable: img_name
If $request->hasFile('p_image') is false you don't define the $img_name variable.
But you always execute the code
Image::create([
'p_image' => $img_name,
'post_id' => $post->id
]);
which is wrong. Change your code to
if($request->hasFile('p_image')){
$img_name = time() . '.' . $request->p_image->getClientOriginalExtension();
$request->p_image->move(public_path('upload'), $img_name);
Image::create([
'p_image' => $img_name,
'post_id' => $post->id
]);
}

Tables Only Update When All Fields Have Been Changed

If I change just the user table items it'll update them (if i change everything in the user table rows). However, it'll only update the user_infos table when I edit everything.
ProfilesController.php
public function update(Request $request)
{
$user_id = Auth()->user()->id;
$id = Auth()->user()->id;
$this->validate($request, array(
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'type' => 'required|string',
'description' => 'string',
'projects' => 'string',
'experience' => 'string',
'links' => 'string',
'status' => 'string'
));
if($request->hasFile('avatar')){
$avatar = $request->file('avatar');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->resize(300, 260)->save( public_path('/images/uploads/avatars/' . $filename ) );
$user = Auth::user();
$user->avatar = $filename;
$user->save();
}
$user = User::find($id);
$user->first_name = $request->input('first_name');
$user->last_name = $request->input('last_name');
$user->email = $request->input('email');
$user->type = $request->input('type');
$user_info = User_Info::find($user_id);
//$user_info = User_Info::where('user_id', $user->id)->first();
$user_info->description = $request->input('description');
$user_info->projects = $request->input('projects');
$user_info->experience = $request->input('experience');
$user_info->links = $request->input('links');
$user_info->status = $request->input('status');
$user->save();
$user_info->save();
return redirect()->route('profile')->withUser($user);
}
settings.blade.php
<div class="twelve wide column">
<div class="ui segment" data-tab="bio">
<form action="{!! action('ProfilesController#update', ['id' => $user->id]) !!}" method="POST" enctype="multipart/form-data" class="ui form">
{{ csrf_field() }}
<h3>Name</h3>
<div class="inline fields">
<div class="eight wide field">
<input type="text" name="first_name" placeholder="First Name" value="{{ $user->first_name }}">
</div><!-- ./Eight Wide Field -->
<div class="eight wide field">
<input type="text" name="last_name" placeholder="Last Name" value="{{ $user->last_name }}">
</div> <!-- ./Eight Wide Field -->
</div><!-- ./Inline Fields -->
<h3 class="header">Profile Image</h3>
<div class="inline fields">
<div class="sixteen wide field">
<input type="file" name="avatar">
</div> <!-- ./Sixteen Wide Field -->
</div> <!-- ./Inline Fields -->
<h3 class="header">Email</h3>
<div class="inline fields">
<div class="sixteen wide field">
<input type="email" name="email" placeholder="Email" value="{{ $user->email }}">
</div> <!-- ./Sixteen Wide Field -->
</div> <!-- ./Inline Fields -->
<h3>Type</h3>
<div class="inline fields">
<div class="sixteen wide field fluid">
<select name="type" class="ui dropdown fluid registerType">
<option value="Developer">Developer</option>
<option value="Designer">Designer</option>
<option value="Fullstack">FullStack</option>
<option value="Client">Client</option>
</select>
</div> <!-- ./Sixteen Wide Field Fluid -->
</div><!-- ./Inline Fields -->
<h3 class="header">Description</h3>
<textarea name="description" id="" cols="30" rows="10" placeholder="Description">{{ isset($user->userInfo->description) ? $user->userInfo->description : "This User Has No Description" }}</textarea>
<h3 class="header">Projects</h3>
<textarea name="projects" id="" cols="30" rows="3" placeholder="Projects">{{ isset($user->userInfo->projects) ? $user->userInfo->projects : "This User Has No Projects Listed" }}</textarea>
<h3 class="header">Experience</h3>
<textarea name="experience" id="" cols="30" rows="3" placeholder="Experience">{{ isset($user->userInfo->experience) ? $user->userInfo->experience : "This User Has No Experience Listed" }}</textarea>
<h3 class="header">Links</h3>
<input type="text" name="links" placeholder="Links" value="{{ isset($user->userInfo->links) ? $user->userInfo->links : "This User Has No Links Listed" }}">
<h3 class="header">Status</h3>
<input type="text" name="status" placeholder="Status" value="{{ isset($user->userInfo->status) ? $user->userInfo->status : "Available" }}">
<br><br>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="submit" class="ui medium fluid blue button" value="Update">
{!! Form::close() !!}
</div><!-- ./Ui Segment -->
</div> <!-- ./Twelve Wide Column -->
Thanks in advance!
Using: Laravel 5.4
In here:
$user->update(); // <--- try this
$user->save();
$user_info->save();
In my ProfilesController.php I had to change the validation for "email" inside public function update(Request $request) a little bit.
From:
$this->validate($request, array(
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'type' => 'required|string',
'description' => 'string',
'projects' => 'string',
'experience' => 'string',
'links' => 'string',
'status' => 'string',
));
To:
$this->validate($request, array(
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users,email,'.$id,
'type' => 'required|string',
'description' => 'string',
'projects' => 'string',
'experience' => 'string',
'links' => 'string',
'status' => 'string',
));

Resources