How To Read Image Base64 In Laravel 9 [duplicate] - php

This question already has answers here:
How to decode a base64 string (gif) into image in PHP / HTML
(5 answers)
Displaying a Base64 images from a database via PHP
(6 answers)
Closed yesterday.
I want to display the encoded BASE64 images from database
here is my controller
public function store(Request $request)
{
$img = $request->image;
$folderPath = "uploads/";
$image_parts = explode(";base64,", $img);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
$fileName = uniqid() . '.png';
$file = $folderPath . $fileName;
Storage::put($file, $image_base64);
User::create($request->all());
dd('SUCCESS');
}
I tried to read the image in this way, but of course it can't because the image name in the database is already encoded BASE64
<table class="table">
<tr>
<td>No</td>
<td>Name</td>
<td>Email</td>
<td>Images</td>
</tr>
#foreach ($users as $user)
<tr>
<td>{{ $loop->iteration }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>
<img src="{{ asset('storage/uploads/'.$user->image) }}" alt="" style="width: 50px">
</td>
</tr>
#endforeach
</table>

Related

How can I display Laravel images on a live server?

I developed a laravel app which is working perfectly on my local machine together with the images. On deployment to live server, the images are no longer visible. I am using shared hosting and my folder structure is like this: public_html containing the public files like upload and main containing the remaining files which should not be visible to the user. Here is my controller `public function
PortfolioAdd(){
return view('frontendbackend.portfoliosection.addportfolio');
}
public function PortfolioStore(Request $request){
$validatedData = $request->validate([
'title' => 'required:portfolio_sections,title',
'description' => 'required:portfolio_sections,description',
]);
$data = new PorfolioSection();
$data->title = $request->title;
$data->description = $request->description;
if ($request->file('image')) {
$file = $request->file('image');
$filename = date('YmdHi').$file->getClientOriginalName();
$file->move(public_path('upload/portfolio_images'),$filename);
$data['image'] = $filename;
}
$data->save();
`and here is my view
<table id="example1" class="table table-bordered table-striped" style = "color:white">
<thead>
<tr>
<th width="5%" style = "color:white">SL</th>
<th style = "color:white">Title</th>
<th style = "color:white">Description</th>
<th style = "color:white">Image</th>
<th style = "color:white">Action</th>
</tr>
</thead>
<tbody>
#foreach($allData as $key => $portfolio )
<tr>
<td style = "color:white"> {{ $key+1 }} </td>
<td> {{ $portfolio->title }} </td>
<td> {{ $portfolio->description }} </td>
<td>
<img src="{{ (!empty($portfolio->image))? url('upload/portfolio_images/'.$portfolio->image):url('upload/no_image.jpg') }}" style="width: 60px; width: 60px;">
</td>
<td>
Edit
Delete
</td>
</tr>
#endforeach
</tbody>
<tfoot>
</tfoot>
</table>
The easiest way to do it is to create a folder inside your public folder e.g portfolio_images.
if ($request->has('photo')) {
$photoName= time() . 'photo' . $request->photo->extension();
$request->photo->move(public_path('portfolio_images'), $photoName);
}
This will save it in public/portfolio_images.
Then in your view
<img id="previewImg" src="{{ asset("portfolio_images/$portfolio->image") }}" alt="Preview your image" height="150">
This should solve it!
First check whether ($portfolio->image) is showing any value by passing it directly in the tag i.e
{{ $portfolio->image}}
if it returns values, check whether the value exists in your folder.
If it exists ch then check your image src.
I would try the following(have not tested)
change this: $file->move(public_path('upload/portfolio_images'),$filename);
to: $file->move(public_path() . 'upload/portfolio_images',$filename);
You must create a symbolink link for that.
The default folder for uploading files is the storage folder.
By running php artisan storage:link, the application will generate a symbolic link that files will be accebile from the public area.
Google symbolic link. You will find the answer.

Exporting Excel from Laravel without installing any library and getting strange chars

Using Laravel 8
My route:
Route::get('socios/export', [SocioController::class, 'export'])->name('socios.export');
My Controller method:
public function export(Request $request)
{
$registros = User::socios()->get();
$content = view('socios.excel', compact('registros'));
$status = 200;
$headers = [
'Content-Type' => 'application/vnd.ms-excel; charset=utf-8',
'Content-Disposition' => 'attachment; filename="filename.xls"',
];
$response = response($content, $status, $headers);
return $response;
}
My 'socios.excel' view:
<table>
<thead>
<tr>
<th>ID</th>
<th>name</th>
<th>...</th>
</tr>
</thead>
<tbody>
#foreach ($registros as $registro)
<tr>
<td>{{ $registro->id }}</td>
<td>{{ $registro->name }}</td>
<td>...</td>
</tr>
#endforeach
</tbody>
</table>
The file exports fine but string like "Dirección" contains wrong chars:
I had try different charset in content-type header but can not fix it.
Some help?
Thanks!

Generate Word File in Laravel PHPWord - problem with add blade

I am beginner in Laravel. I use in my project Laravel 5.8.
I have this code for generate Word file:
$phpWord = new \PhpOffice\PhpWord\PhpWord();
$month = $request->input('month');
if ($month == null) {
$now = Carbon::now();
$month = $now->month;
}
$events = $this->frontendGateway->getEventCalendarDownload($request, $month);
$logo = public_path('assets/images/logo3.jpg');
$view_content = View::make('psCMS.prints.events-view', ['events' => $events, 'logo' => $logo])->render();
$section = $phpWord->addSection();
$text = $section->addText('aaaaaaaa');
$text = $section->addText('bbbbbbbbbb');
$text = $section->addText('ccccccccccc');
$text = $section->addText($view_content);
//ob_clean();
$fileName = 'Event_calendar' . '-' . now()->toDateString() . '.doc';
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save($fileName);
header('Content-Type: application/octet-stream');
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
header("Content-Disposition: attachment; filename=$fileName");
ob_clean();
readfile($fileName);
and this is my Blade file:
<div id="header" class="fontSize14">
<table width="100%">
<tr>
<td align="left" style="width: 20%;">
<img src="{{ $logo }}" class="logo" />
</td>
<td align="left" style="width: 80%;">
<span class="fontSize19"><b>my name</b></span><br />
street<br />
</td>
</tr>
</table>
</div>
<div id="content" class="fontSize11">
<b class="fontSize19">Kalendarz wydarzeń</b><br /><br />
<table width="100%">
<thead style="background-color: lightgray;">
<tr>
<th>#</th>
<th>Data</th>
<th>Godzina</th>
<th>Nazwa imprezy</th>
<th>Miejsce</th>
</tr>
</thead>
<tbody>
#foreach($events as $event)
#php
$hourFromX = explode(":", $event->hour_from);
$hourToX = explode(":", $event->hour_to);
$hourFrom = $hourFromX['0'].":".$hourFromX['1'];
$hourTo = $hourToX['0'].":".$hourToX['1'];
#endphp
<tr>
<th scope="row">{{ $loop->iteration }}</th>
<td>{{ $event->date_from }}</td>
<td align="left">{{ $hourFrom }}-{{ $hourTo }}</td>
<td align="left">{{ $event->title }}</td>
<td align="left">#if(isset($event->localization)) {{ $event->localization->name }},
{{ $event->localization->city }}
{{ $event->localization->street }} #endif</td>
</tr>
#endforeach
</tbody>
</table>
</div>
When I run this code, I have error: Word file is corrupted.
When I comment this line:
$text = $section->addText($view_content);
Word file is okey. Generated file was open in Word without any problems.
How can I repair it?
Can you try adding addHtml instead of addText
\PhpOffice\PhpWord\Shared\Html::addHtml($section, $view_content , false, false);

Laravel Showing my Data Arrays to index.blade.php - Undefined Offset 1

Im trying to show all my data in database to my index.blade.php, however, there's an error that is showing Undefined Offset 1. I used arrays. There's no data that is showing in my table form. here is my code. Please guide me im new to Laravel thanks.
My VIEW
Here is where the problem occurs
<div class="form-group">
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<th>Image Name</th>
<th>Action</th>
</tr>
#foreach($promotions->$promotion)
<tr>
<th>{{ $promotion->promotion_image }}</th>
<th>Update</th>
<th>Remove</th>
</tr>
#endforeach
</table>
</div>
</div>
My CONTROLLER INDEX FUNCTION
public function index()
{
$promotions = Promotion::all();
return view('admin.airlineplus.promotions.index')->with('promotions', $promotions);
}
My CONTROLLER STORE FUNCTION
Here is where I store my data using arrays
public function store(Request $request)
{
$this->validate($request, [
'promotion_image' => 'required'
]);
if ($request->has('promotion_image'))
{
//Handle File Upload
$promotion = [];
foreach ($request->file('promotion_image') as $key => $file)
{
// Get FileName
$filenameWithExt = $file->getClientOriginalName();
//Get just filename
$filename = pathinfo( $filenameWithExt, PATHINFO_FILENAME);
//Get just extension
$extension = $file->getClientOriginalExtension();
//Filename to Store
$fileNameToStore = $filename.'_'.time().'.'.$extension;
//Upload Image
$path = $file->storeAs('public/promotion_images',$fileNameToStore);
array_push($promotion, $fileNameToStore);
}
$fileNameToStore = serialize($promotion);
}
else
{
$fileNameToStore='noimage.jpg';
}
foreach ($promotion as $key => $value) {
$promotionImage = new Promotion;
$promotionImage->promotion_image = $value;
$promotionImage->save();
}
return redirect('/admin/airlineplus/promotions/create')->with('success', 'Image Inserted');
}
Guide me through all of this please thanks
You have made a slight error with your foreach type changing it to this
<div class="form-group">
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<th>Image Name</th>
<th>Action</th>
</tr>
#foreach($promotions as $promotion)
<tr>
<th>{{ $promotion->promotion_image }}</th>
<th>Update</th>
<th>Remove</th>
</tr>
#endforeach
</table>
</div>
foreach has the first option is the variable to loop through and the second is the variable for each of the loops
http://php.net/manual/en/control-structures.foreach.php

create csv download for table results

I need to create a csv file with a download button for my table results view. I am using Laravel framework and am unsure on how exactly to do this.
My controller to get the data.
public function reportFailedPayments(){
$startdate = Input::get('startdate');
$enddate = Input::get('enddate');
$status = Input::get('status');
$data = Payment::with('purchase', 'history', 'history.billingInformation', 'purchase.user', 'purchase.productInstance', 'purchase.productInstance.product', 'billingInformation')
->where('Status', '=',$status)->whereBetween('Payment_Date', array($startdate, $enddate))->orderBy('Payment_Date','desc')->get();
return View::make('admin.reports.failedPayments.report', array('payments'=>$data));
}
}
And here is my table view. Just needing some advice on how exactly to create the DL for the csv.
<table class='list'>
<thead>
<tr>
<th>Customer Name</th>
<th>Customer Email</th>
<th>Product Name</th>
<th>Purchase Date</th>
<th>Initial Payment Date</th>
<th>Last Payment Date</th>
<th>Billing Method</th>
<th>Transaction Code</th>
<th>Transaction Message</th>
</tr>
</thead>
<tbody>
#foreach($payments as $p)
<tr>
<td>{{ $p->purchase->user->Last_Name.', '.$p->purchase->user->First_Name }}</td>
<td>{{ $p->purchase->user->Email }}</td>
<td>{{ $p->purchase->productInstance->product->Name }}</td>
<td>{{ $p->purchase->Purchase_Date }}</td>
<td>{{ $p->Payment_Date }}</td>
<td>{{ $p->lastHistory()->Process_Time }}</td>
<td>{{ $p->lastHistory()->billingInformation->Payment_Type == PaymentType::PayPal ? "PayPal" :
CreditCardType::ToString($p->lastHistory()->billingInformation->CCType)." Ending In ".$p->lastHistory()->billingInformation->CCLast4 }}</td>
<td>{{ $p->lastHistory()->Trans_Response_Code }}</td>
<td>{{ $p->lastHistory()->Trans_Response_Text }}</td>
</tr>
#endforeach
</tbody>
</table>
Let me start by saying that I won't write all the code for you. This just isn't the purpose of StackOverflow...
However I hope I can point you in the right direction with this answer.
Your problem can be split in two tasks. One being generating the CSV file and then serve the download.
Generating the CSV file
You'll find a lot of code snippets on the internet. Here's one I found and modified a bit
$csvData = $yourCollection->toArray();
$filename = tempnam(sys_get_temp_dir(), 'csv_'); // create a temporary file in the system's default tmp directory
$file = fopen($filename, 'w');
foreach($csvData as $row){
fputcsv($file, $row, ';'); // 3rd parameter is optional (default: ',')
}
fclose($file);
Now we have a csv file in our temp folder, ready to be downloaded. Laravel gives you a very way to download files.
Serving the file for download
In your controller action:
$response = Response::download($filename);
unlink($filename); // lets not forget to delete the file or they will pile up in your temp folder
return $response;
Maybe you also need to send some additional headers (e.g. for specifying a filename that the user sees) but I'll leave that up to you.
And here are some references to the functions used in the code:
Laravel Response::download
PHP fputcsv()
PHP tempnam()

Categories