How to update an uploaded image on laravel - laravel

This is my blade
<a href="{{action('ProduitController#edit', $value->id)}}" class=" btn btn-warning btn-xs">
<i class="glyphicon glyphicon-pencil"></i>
</a>
<td><img src='{{ asset('public/images/'.$value->photo) }}' style="width:70px; height:70px; float:left; border-radius:50%; margin-right:25px;"></td>
This is my contoller
public function update(Request $request, $id)
{
$prod= \App\Produit::find($id);
$prod->identification=$request->get('identification');
$prod->nom=$request->get('nom');
$prod->description=$request->get('description');
$prod->quantite=$request->get('quantite');
$prod->categorie_id=$request->get('categorie_id');
$prod->prix=$request->get('prix');
$prod->marque_id=$request->get('marque_id');
$prod->fournisseur_id=$request->get('fournisseur_id');
if($request->hasfile('photo'))
{
$file = $request->file('photo');
$extension = $file->getClientOriginalExtension();
$filename =time().'.'.$extension;
$file->move('public/images', $filename);
$prod->photo =$filename;
}
$prod->save();
Session::flash('message','le produit '.$request->nom.' a été Modifier avec succès');
return redirect('/produit');
}
This is the route for update
Route::resource('ventes','VenteController');
If someone has some proposition I will be grateful

checkout your controller catch the 'photo' file by dd it or whatever
if it doesnt have photo file you need to recheck your blade file is it already sending correct parameter or not
if you haven't any issue with insert photo, it should be controller update dont have the photo file, check out your blade to fix the issue, and maybe providing the store controller might help us giving solution

Related

How to add button to open url with parameter in datatables Laravel 8

I have some data shown in my datatable view, I want to add button to each data to open detail page which can show more detail information
public function Task(Request $request)
{
if ($request->ajax()) {
$data = DB::table('posts')
->where('jabatan', Auth::user()->jabatan)
->select('user_id', 'name', DB::raw('count(user_id) as total'))
->selectRaw('SUM(status = "Selesai") as selesai')
->selectRaw('count(user_id) - SUM(status = "Selesai") as belum')
->groupBy('name')
->groupBy('user_id')->get();
return Datatables::of($data)
->addColumn('action', function ($row) {
$btn = ' <span class="fas fa-eye"></span>';
return $btn;
})
->rawColumns(['action'])
->addIndexColumn()
->make(true);
}
return view('task.Task');
}
the button can appear in my datatable, but it will open %7B%7Broute('detail.index',$row->user_id)%7D%7D ,
If in a html table I can use <a class="btn btn-info btn-sm" href="{{ route('detail.index',$post->id) }}">Show</a>
how to make the button to open /detail in url? thanks in advance
as your in already in php so don't use {{ }} blade syntax use
$btn = '<span class="fas fa-eye"></span>';

Laravel 8, image url rerieved from database does not return image

I have been struggling with this problem for quite a few hours. My problem is that I have an image url saved in my database and when i retrieve it I try to display it in my index.blade.php. The weird part is I had used the same code in an older project and it worked, but I turned on the older project and it does not work there anymore either. I have done php artisan storage:link and from what i see the link is correct but the images are displayed as broken, I have looked up various solution but all of it lead to a dead end, because the url just doesnt want to display the image. The image url is saved in this form http://127.0.0.1:8000/storage/public/vsX9ihmRknGWLXtNRmxgCXV3ckqhlFoBlyuMoejB.png
My index.blade.php tbody
<tbody>
#foreach($companies as $company)
<tr>
<td scope="row">{{$company->id}}</td>
<td>{{$company->name}}</td>
<td>{{$company->email}}</td>
<td><img class="class='img-fluid rounded mb-3 mb-lg-0 ml-md-0" src="{{$company->logo}}"></td>
<td>{{$company->url}}</td>
<td>
<a href="{{route('company.edit', $company->id)}}" class="float-left">
<button type="button"
class="btn btn-primary mr-2">{{__('Edit')}}</button>
</a>
<form action="{{route('company.delete',$company->id)}}" method="POST"
class="float-left">
{{method_field('DELETE')}}
#csrf
<button type="submit"
class="btn btn-danger btn-sn">{{__('Delete')}}</button>
</form>
</td>
</tr>
#endforeach
</tbody>
How I call it from my Companiescontroller
public function index(): Renderable
{
$companies = $this->company->all();
return view('company.index', compact('companies'));
}
How I store my image url
public function store(Request $request): RedirectResponse
{
$request->validate([
'name' => 'required',
'email' => '',
'logo' => 'dimensions:min_width:100,min_height:100',
'url' => ''
]);
$parameters = $request->all();
if ($request->logo !== null) {
$image = $request->logo->store('public');
$parameters['logo'] = URL::to('/') . '/storage/' . $image;
}
$this->company->create($parameters);
return redirect()->route('company.index');
}
I am not sure if this is enough, but i guess these are primary parts.
By default php artisan storage:link create a symlink with storage/app/public so move your image from storage/public to storage/app/public. Then you can access through http://127.0.0.1:8000/storage/vsX9ihmRknGWLXtNRmxgCXV3ckqhlFoBlyuMoejB.png

Laravel 8 upload and download file

I am trying to put a download button within a dataTable in Laravel but am getting the following error: "DataTables warning: table id=dataTableBuilder - Exception Message: Undefined variable: fileName".
This is my ReportController snippet:
public function store(CreateReportRequest $request)
{
$request->validate([
'file_path' => 'required|mimes:pdf|max:2048'
]);
$report = new Report;
if($request->file()) {
$fileName = time().'_'.$request->file_path->getClientOriginalName();
$filePath = $request->file('file_path')->storeAs('reports', $fileName, 'public');
$report->name = time().'_'.$request->file_path->getClientOriginalName();
$report->file_path = '/storage/' . $filePath;
$report->save();
Flash::success('Pop saved successfully.');
}
return redirect(route('reports.index'));
}
public function download($fileName)
{
$file_path = storage_path('reports') . "/" . $fileName;
return Response::download($file_path);
}
This is my view snippet (button for the download):
<a href="{{ route('reports.download', $fileName) }}" class='btn btn-ghost-info'>
<i class="fa fa-download"></i>
</a>
And this is my routes snippet:
Route::post('/reportdownload/{fileName}', [App\Http\Controllers\ReportController::class, 'download'])->name('reports.download');
Please help me figure out what I am doing wrong.
try catching file with its {ID} in web.php and view as well
for example: WEB.PHP
Route::post('/reportdownload/{id}', [App\Http\Controllers\ReportController::class, 'download'])->name('reports.download');
view:
<a href="{{ route('reports.download', $id) }}" class='btn btn-ghost-info'>
<i class="fa fa-download"></i>
</a>

How to Set & Get Session Data in Laravel Package Development

I am developing a package with a contact form in Laravel. I'm trying to set & get session data, but it's not working with the following.
View
#if(session('success'))
<div class="alert alert-success alert-dismissible">
×
{{session('success')}}
</div>
#endif
Controller
public function store(Request $request)
{
//Validation
$request->validate([
'email'=>'required|max:50|unique:contact_forms,email'
]);
//Data
$contact_form = new ContactForm();
$contact_form->full_name = $request->full_name;
$contact_form->mobile = $request->mobile;
$contact_form->email = $request->email;
//Save
$contact_form->save();
//Return back
return back()->with('success','Record inserted successfully');
}
Route
Route::group(['namespace' => 'W3public\ContactForm\Http\Controllers'], function () {
Route::get('contact-us', 'ContactFormController#index');
Route::post('contact-us', 'ContactFormController#store')->name('contact-us');
});
How can I set/get session data in package development in Laravel?Thanks in advance.
Best way of doing this is flash session messages
Redirect as
$request->session()->flash('alert-success', 'Record inserted successfully!');
and in your view file
<div class="flash-message">
#foreach (['danger', 'warning', 'success', 'info'] as $msg)
#if(Session::has('alert-' . $msg))
<p class="alert alert-{{ $msg }}">{{ Session::get('alert-' . $msg) }} ×</p>
#endif
#endforeach

Upload multiple image for posts in laravel 5.5

I want to know how can I have multiple image in my posts?
Currently I have ImageController which I tried to get images and attach to post_id but the issue of that is if I use that method because I still didn't save my post there will be no id to be attached to images.
Any idea on that?
Please take a look for better understanding:
https://ibb.co/huC1Qw
blade:
<form action="upload" id="upload" enctype="multipart/form-data" method="post">
<div class="row">
<div class="col-md-6"><input type="file" class="form-control" name="files[]" multiple></div>
<div class="col-md-6"><input type="submit" class="btn btn-success" value="Upload now"></div>
</div>
</form>
controller:
public function upload(Request $request) {
$files = $request->file('file');
if (!empty($files)):
foreach($files as $file):
Storage::put($file->getClientOriginalName(), file_get_contents($file));
endforeach
endif;
return \response::json(array('success' => true));
}
route:
Route::post('/upload', 'ImageController#upload');
Approach 1.
Return $request->photos or put them in the session while you are not done yet with post submitting. After it was submitted assign references.
Approach 2.
First, save them in [temp] then move and assign to the post.
Approach 3.
Create a default record in your database, assign images to that record, get the record_id post_id and return to the form that post_id. Then just populate that post with your post_id.
Approach 4.
It is not the good choice to save images in the database, just save them as file and place de reference link in the database, or find them by the id of the folder that has the same id as your post, or beautify links to them ... definitely not by saving them to database. It is my opinion, everyone has to find his/her way for an easy living.
Try this :-
use App\ProductsPhoto; \\ add in top of controller
public function upload(Request $request) {
$product = Product::create($request->all());
if ($request->hasFile('files')) {
$files = $request->file('files');
foreach($files as $file){
$productsPhotos = new ProductsPhoto;
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$fileName = str_random(5)."-".date('his')."-".str_random(3).".".$extension;
$destinationPath = 'images/ProductsPhotos'.'/';
$file->move($destinationPath, $fileName);
$productsPhotos->product_id = $product->id,
$productsPhotos->filename = $fileName;
$productsPhotos->save();
}
}
return 'Upload successful!';
}
Hope it helps!
For upload and display images
if you are using two tables.
upload.blade.php
<form method="post" action="{{ url('/uploads') }}" enctype="multipart/form-data">
<input type="file" id="file" name="files[]" class="inputfile" value="{{ old('arquivo') }}" multiple />
Controller
public function show() {
$images = DB::select('SELECT * FROM table1 INNER JOIN table2 on table1.id = table2.id_file');
return view('index')->with('images', $images);
}
public function upload(yourRequest $request) {
$images = model1::create($request->all());
foreach ($request->files as $file) {
$filename = $file->store('/uploads');
modelFiles::create([
'id_file' => $images->id,
'file' => $filename
]);
}
return redirect()->action('Controller#show')->withInput(Request::only('name'));
}
index.blade.php
#foreach($images as $i)
<div class="item {{ $loop->first ? 'active' : '' }}">
<img src="{{ asset("storage/$i->file") }}" alt="...">
</div>
#endforeach

Resources