How to image update using laravel5 - laravel-5

I don't know how to edit image using laravel5. When I update my image file It show this error:
FatalErrorException in SiteadminController.php line 1719:
Class 'App\Http\Controllers\Image' not found
Controller
public function siteadmin_update_ads(Request $request)
{
$post = $request->all();
$cid=$post['id'];
// $img=$post['ads_image'];
$v=validator::make($request->all(),
[
'ads_title'=>'required',
'ads_url' => 'required',
]
);
if($v->fails())
{
return redirect()->back()->withErrors($v->errors());
}
//$image = Image::find($cid);
else
{
$image = Image::find($cid);
if($request->hasFile('ads_image'))
{
$file = $request->file('ads_image');
$destination_path = '../assets/adsimage/';
$filename = str_random(6).'_'.$file->getClientOriginalName();
$file->move($destination_path, $filename);
$image->file = $destination_path . $filename;
$data=array(
'ads_title'=>$post['ads_title'],
'ads_url'=>$post['ads_url'],
'ads_image'=>$post['ads_image'],
);
}
// $image->caption = $request->input('caption');
// $image->description = $request->input('description');
$image->save();
}
// $i = DB::table('le_color')->where('id',$post['id'])->update($data);
$i=Ads_model::update_ads($data,$cid);
if($i>0)
{
Session::flash ('message_update', 'Record Updated Successfully');
return redirect('siteadmin_manageads');
}
else {
return Redirect('siteadmin_editads');
}
}
Model
public static function update_ads($data,$cid)
{
return DB::table('le_ads')->where('id',$cid)->update($data);
}
View
<div class="item form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Upload Image*</label>
<div class="col-md-9 col-sm-6 col-xs-12">
<input type='file' id="field" class='demo left' name='ads_image' data-type='image' data-max-size='2mb'/><br>
<img src="{{ url('../assets/adsimage/').'/'.$row->ads_image}}" style="height:90px;">
</div>
</div>

I don't know what is that Image, so I am at least possible help to you. But I'll try to solve it.
What you can do is:
Add backslash \ before the Image. It should look like this: \Image::find($cid);
Or else, it is a Intervention package: you need to import the Facade of Intervention Package.
add use Intervention\Image\Facades\Image;
I hope this helps you out.

you are missing the 'use' import statement for class image so its trying to find the class in the current namespace which is wrong assuming your model is stored at App namespace then add the below in the begining of controller
use App\Image

Related

Uploading files with infyom generator

I am trying to upload a file with laravel using the code generated by the infyom generator. The file seems to be uploaded but this is what is shown on the application when I view the report (C:\xampp\tmp\php7925.tmp). Provided below is the code for my application.
Thank you so much and really appreciate the help in this project.
rgds,
Form
<!-- Inf File Field -->
<div class="form-group col-sm-6">
{!! Form::label('inf_file', 'Attachments:') !!}
{!! Form::file('inf_file') !!}
</div>
Controller
{
$input = $request->all();
$infrastructure = $this->infrastructureRepository->create($input);
$file = $request->file('inf_file');
$file = $request->inf_file;
if ($request->hasFile('inf_file')){
//
if ($request->file('inf_file')->isValid()){
}
}
Flash::success('Infrastructure saved successfully.');
return redirect(route('infrastructures.index'));
}
This is how you display when you view your records,
<!-- Inf File Field -->
<div class="form-group">
{!! Form::label('inf_file', 'Attachements:') !!}
<a download href="{{ asset($infrastructure->inf_file) }}">Download</a>
</div>
Managed to solve it.
public function store(CreateinfrastructureRequest $request)
{
$input = $request->all();
if ($request->hasFile('inf_file')){
//Validate the uploaded file
$Validation = $request->validate([
'inf_file' => 'required|file|mimes:pdf|max:30000'
]);
// cache the file
$file = $Validation['inf_file'];
// generate a new filename. getClientOriginalExtension() for the file extension
$filename = 'Infras-' . time() . '.' . $file->getClientOriginalExtension();
// save to storage/app/infrastructure as the new $filename
$InfrasFileName = $file->storeAs('infrastructure', $filename);
$path = "/storage/app/public/".$InfrasFileName;
}
$input['inf_file'] = $path;
$infrastructure = $this->infrastructureRepository->create($input);
Flash::success('Infrastructure saved successfully. ' . $path);
return redirect(route('infrastructures.index'));
}

getMimeType() before moving file in Laravel

This a part of my app I'm using to put a section that admin can choose the category of the file from...
File Model
namespace App\Models;
use App\Traits\Categorizeable;
use Illuminate\Database\Eloquent\Model;
class File extends Model
{
use Categorizeable;
protected $primaryKey = 'file_id';
protected $guarded = ['file_id'];
public function packages()
{
return $this->belongsToMany(Package::class, 'package_file');
}
}
Anyway I used a trait for it...
after that it is my view:
<div class="form-group">
<label for="categorize"> categories :</label>
<select name="categorize[]" id="categorize" class="select2 form-control" multiple>
#foreach($categories as $cat)
<option value="{{$cat->category_id}}"
{{isset($file_categories) && in_array($cat->category_id,$file_categories) ? 'selected' :'' }}>
{{$cat->category_name}}</option>
#endforeach
</select>
</div>
at last this is my FilesController:
public function store(Request $request)
{
// $this->validate();....
//after validation
$new_file_name = str_random(45) . '.' . $request->file('fileItem')->getClientOriginalExtension();
$result = $request->file('fileItem')->move(public_path('files'), $new_file_name);
if ($result instanceof \Symfony\Component\HttpFoundation\File\File) {
$new_file_data['file_name'] = $new_file_name;
$new_file_data = File::create([
'file_title' => $request->input('file_title'),
'file_description' => $request->input('file_description'),
'file_type' => $request->file('fileItem')->getMimeType(),
'file_size' => $request->file('fileItem')->getClientSize(),
]);
if ($new_file_data) {
if ($request->has('categorize')) {
$new_file_data->categories()->sync($request->input('categorize'));
}
return redirect()->route('admin.files.list')->with('success', 'message');
}
}
}
Now what my problem is that as you see file() saves a .tmp file first and I need to use getMimeType() before I move it, how to modify my code?
What is the best way to do that?
App is giving me an Error
Save the mime type as a variable before you move the file and use it in the create function
$new_file_name = str_random(45) . '.' . $request->file('fileItem')->getClientOriginalExtension();
$mime_type = $request->file('fileItem')->getMimeType();
$file_size = $request->file('fileItem')->getClientSize();
$result = $request->file('fileItem')->move(public_path('files'), $new_file_name);
if ($result instanceof \Symfony\Component\HttpFoundation\File\File) {
$new_file_data['file_name'] = $new_file_name;
$new_file_data = File::create([
'file_title' => $request->input('file_title'),
'file_description' => $request->input('file_description'),
'file_type' => $mime_type,
'file_size' => $file_size,
]);

Trying to get a variable pagination to show me 3 different types of paginations

Here is my Index:
<div class="page-sizer">
<a class="page numbers" href="{{$references->pagination(10)}}">10</a>
<a class="page numbers" href="{{$references->pagination(30)}}">30</a>
<a class="page numbers" href="{{$references->pagination(100)}}">100</a>
<button href="qweqwe.qweqwe" class="btn btn-info float-right>112e1e1e1e"></button>
</div>
My AdminreferenceController:
public function index()
{
$references = Reference::orderBy('priority', 'desc')->orderBy('id', 'desc')->paginate(50);
return view('admin.reference.index', ['references' => $references]);
}
and my Lengthawarepaginator:
public function __construct($items, $total, $perPage, $currentPage = null, array $options = [])
{
foreach ($options as $key => $value) {
$this->{$key} = $value;
}
$this->total = $total;
$this->perPage = $perPage;
$this->lastPage = max((int) ceil($total / $perPage), 1);
$this->path = $this->path !== '/' ? rtrim($this->path, '/') : $this->path;
$this->currentPage = $this->setCurrentPage($currentPage, $this->pageName);
$this->items = $items instanceof Collection ? $items : Collection::make($items);
}
. i currently get the error Method Illuminate\Database\Eloquent\Collection::pagination does not exist.
I want to have 3 buttons that show 3 different kinds of paginations like in stackoverflow in the search bar at the bottom.
You are calling pagination in collection try like this
first you need to include the DB class before class deceleration
use Illuminate\Support\Facades\DB;
Then change the query like this
$references = DB::table('reference')->orderBy('priority', 'desc')->orderBy('id', 'desc')->paginate(5o);
return view('admin.reference.index', ['references' => $references]);
In you view you need to access like this
{{ $references->links() }}
https://laravel.com/docs/5.7/pagination
i have currently changed the pagination completly. i wrote a url with
/x/y/perpage/10,
/x/y/perpage/30,
/x/y/perpage/100,
i made a new route for it
route::('/x/perpage/{count})'
and changed my AdminReferenceController to
public function index($perpage = false)
{
if(!$perpage) {
$perpage = 10;
}
$references = Reference::orderBy('priority', 'desc')->orderBy('id', 'desc')->paginate($perpage);
I couldn't get time to work this out. But I found you calling pagination() instead of paginate. See my suggetion
<div class="page-sizer">
<a class="page numbers" href="{{$references->paginate(10)}}">10</a>
<a class="page numbers" href="{{$references->paginate(30)}}">30</a>
<a class="page numbers" href="{{$references->paginate(100)}}">100</a>
<button href="qweqwe.qweqwe" class="btn btn-info float-right>112e1e1e1e"></button>
</div>
Here I removed the paginate from index() and returns collection.
public function index()
{
$references = Reference::orderBy('priority', 'desc')->orderBy('id', 'desc');
return view('admin.reference.index', ['references' => $references]);
}
Hope this helps you.

How to Set or retrieve old Path image when we not update the image in the form multiple images in Codeigniter 2.2.6

I have edit form in codeigniter in that form i have 15 more image file while i update the image it updating in database but even am not update the images in the form it goes and save as null or empty path .But i need solution for that when am not update all 15 files should retrive the same old image path which it is stored in database.Please Could you guys give better solution for this.
My Edit Form
controller:
if($this->input->post('submit'))
{
if($_FILES['file']['name']!='')
{
$filename = $_FILES['file']['name'];
$file_name1 = "upload_".$this->get_random_name()."_".$filename;
$_SESSION['file_upload']=$file_name1;
$file ="uploads/images/".$file_name1;
}
if($_FILES['file1']['name']!='')
{
$filename = $_FILES['file1']['name'];
$file_name2 = "upload_".$this->get_random_name()."_".$filename;
$_SESSION['file_upload']=$file_name2;
$file ="uploads/images/".$file_name2;
}
$query = $this->scener_model->popular_upload($file_name1,$file_name2)
}
If your is empty then pass hidden input value or else pass newly uploaded value like this..
if(!empty($_FILES()){
//your uploaded value here
} else {
//hidden attribute value
}
if($this->input->post('submit1')){
$titlemain = $this->input->post('title_main');
$price = $this->input->post('price');
$package = $this->input->post('package');
$titleinner = $this->input->post('title_inner');
$city_package = $this->input->post('city_packge');
if(!empty($count =count($_FILES['file1']['name']))){;
for($i=0; $i<$count;$i++){
$filename1=$_FILES['file1']['name'][$i];
//print_r($filename);exit;
$filetmp=$_FILES['file1']['tmp_name'][$i];
$filetype=$_FILES['file1']['type'][$i];
$images = $_FILES['file1']['name'];
$filepath="uploads/images/".$filename1;
move_uploaded_file($filetmp,$filepath);
}
$filename1 = implode(',',$images);
}
else{
$filename1=$this->input->get('iti_image2') ;
//print_r( $data['newz1']);exit;
}
my view page:
<div class="col-sm-8">
<input type="button" id="get_file" value="Grab file">
<?php
$imss= $result->iti_image2;
?>
<input type="file" id="my_file" name="file3[]" value="<?php echo $imss ?>" multiple/>
<div id="customfileupload">Select a file</div>
<input type="hidden" class="btn btn info" id="image" name="iti_image2" accept="image" value="<?php echo $result->iti_image2; ?>" multiple/ >
</div>
<script>
document.getElementById('get_file').onclick = function() {
document.getElementById('my_file').click();
};
$('input[type=file]').change(function (e) {
$('#customfileupload').html($(this).val());
});
</script>
</div>
my Model:
function itinerary_updte($filename4,$filename5){
$update_itinerarys = array(
'iti_image2' =>$filename4,
'iti_image3' =>$filename5
);
$this->db->where('id', $id);
$result = $this->db->update('sg_itinerary', $update_itinerarys);
return $result;
}
Finally guys i found a solution for image updating follwing some tutorials see the link
"http://www.2my4edge.com/2016/04/multiple-image-upload-with-view-edit.html"
thanks buddies who are give the logic and commenting on my post and thanks alot #ankit singh #Lll

$_FILES['imagem'] is undefined in Firefox

My website is built using Codeigniter, and there's an area for users to modify their information. This area allows users to choose a profile picture, and when editing it, the selected picture is previewed. In case they don't choose a new one, there's a hidden field storing its name, which is passed to the controller to specify the same image name, but if the user decides to change it, the new name is passed to the controller.
public function edit($id)
{
$this->input->post('tipo_usuario') === 'F' ? $validator = 'editar_pessoa_fisica' : $validator = 'editar_pessoa_juridica';
if ($this->form_validation->run($validator)) {
$data = array();
$data['nome_razao_social'] = $this->input->post('nome_razao_social');
$data['nome_responsavel'] = $this->input->post('nome_responsavel');
$data['nome_fantasia'] = $this->input->post('nome_fantasia');
$data['cpf_cnpj'] = $this->input->post('cpf_cnpj');
$data['telefone'] = $this->input->post('telefone');
$data['telefone_2'] = $this->input->post('telefone_2');
$data['email'] = $this->input->post('email');
$data['novo_email'] = $this->input->post('novo_email');
$data['senha'] = md5($this->input->post('senha'));
$data['cep'] = $this->input->post('cep');
$data['logradouro'] = $this->input->post('logradouro');
$data['id_cidade'] = $this->input->post('id_cidade');
$data['id_estado'] = $this->input->post('id_estado');
$data['numero'] = $this->input->post('numero');
$data['complemento'] = $this->input->post('complemento');
$data['tipo_usuario'] = $this->input->post('tipo_usuario');
/*
HERE IS IN CASE THE USER DOES NOT CHANGE HIS PROFILE PICTURE
*/
$data['imagem'] = $this->input->post('imagem_old');
$data['url'] = $this->input->post('url');
// Nova senha?
if ($this->input->post('novasenha') !== '') {
$data['senha'] = md5($this->input->post('novasenha'));
} else {
$data['senha'] = $this->input->post('senha');
}
/*
HERE IS IN CASE THE USER CHANGES HIS PROFILE PICTURE
*/
// Nova imagem?
if ($_FILES['imagem']['name'] !== '') {
$data['imagem'] = $_FILES['imagem']['name'];
}
// Novo e-mail?
if ($this->input->post('email') !== $this->input->post('novoemail')) {
$data['novo_email'] = $this->input->post('novoemail');
$this->Usuarios_model->update($data, $id);
$this->Usuarios_model->send_confirmation_email($data['novo_email'], $data['email']);
}
if ($this->input->post('novo_novo_email') !== $this->input->post('novo_email')) {
$data['novo_email'] = $this->input->post('novo_novo_email');
$this->Usuarios_model->update($data, $id);
$this->Usuarios_model->send_confirmation_email($data['novo_email'], $data['email']);
}
if ($this->Usuarios_model->update($data, $id)) {
$this->upload->do_upload('imagem');
$this->session->set_flashdata('message', 'Dados alterados');
echo json_encode(array(
'redirect' => '/usuario/painel'
));
}
} else {
echo json_encode(array(
'type' => 'validation',
'message' => validation_errors(),
));
}
}
This is the HTML:
<form action="/auto/usuario/edit/<?php echo $id_usuario; ?>" method="POST" class="formulario" enctype="multipart/form-data">
<input type="hidden" name="tipo_usuario" value="F"/>
<div class="p100">
<span class="titulo">Foto de Perfil</span>
<div class="imagem_destaque img_perfil image-trigger">
<div class="file-upload-trigger">
<input type="file" name="imagem" class="none file-chooser"/>
<img src="/uploads/perfil/<?php echo $u['imagem'] ?>" class="preview more"/>
</div>
</div>
<input type="hidden" name="imagem_old" value="<?php echo $u['imagem']; ?>"/>
</div>
With Google Chrome, it works fine, but in Firefox 45, if I do not choose a new image, an error is thrown:
Severity: Notice
Message: Undefined index: imagem
Filename: controllers/Usuario.php
Line Number: 362
It only works locally.
If you do not upload a new image, your $_FILES[] is undefined, as the error says. To check if the user has changed his image you should do:
if ( isset($_FILES['imagem']['name']) ) {
$data['imagem'] = $_FILES['imagem']['name'];
}

Resources