I have a foreach loop and slider, and into loop I have background image. Background image is working for some, but not all of them.
This is my code:
#if($products)
#foreach($products as $product)
<div class="swiper-slide text-center">
<a href="{{url('products/'.$product->id)}}">
<div class="border-2"
style="background-image: url({{src($product,'main_image')}})"></div>
<div class="mt-1">{{$product->title}}</div>
</a>
</div>
#endforeach
#endif
src is a function
function src($object,$slug,$thumb_size = null) {
$table = $object->getTable();
$width = ($thumb_size)?explode('/',$thumb_size)[0]:false;
$height = ($thumb_size)?explode('/',$thumb_size)[1]:false;
if($attachment = $object->attachments($slug)->first()) {
if($width && $height) {
$src = url("/uploads/".$table."/thumb_{$width}-{$height}_".$attachment->file);
} else {
$src = url("/uploads/".$table."/".$attachment->file);
}
} else {
if($width && $height) {
if(file_exists("uploads/defaults/thumb_{$width}-{$height}_default.png")) {
$src = url('')."/uploads/defaults/thumb_{$width}-{$height}_default.png";
} else {
Image::make("default.png")->fit($width,$height)->save("uploads/defaults/thumb_{$width}-{$height}_default.png");
$src = url('')."/uploads/defaults/thumb_{$width}-{$height}_default.png";
}
} else {
$src = url('')."/default.png";
}
}
return $src;
}
Related
I want to ask for solution when generating barcode using if conditional based on number lenght.
If I generate barcode with code like this below, the result absolutely no problem.
<?php $i = 1; ?>
#foreach ($produks as $item)
#if ($i <= 5)
<div class="box">
<div class="title">{{ $item['nama'] }}</div>
{{ DNS1D::getBarcodeHTML($item['sku'], 'EAN13') }}
<div class="sku">{{ $item['sku'] }}</div>
</div>
<?php $i++; ?>
#else
<div style="clear: both"></div>
<?php $i = 1; ?>
#endif
#endforeach
But if I use "if conditional" with strlen in there, I've got error. I want to print a barcode based on the length of the number
#foreach ($produks as $item)
#if ($i <= 5)
<div class="box">
<div class="title">{{ $item['nama'] }}</div>
#if (strlen($item['sku']) == 12)
{{ DNS1D::getBarcodeHTML($item['sku'], 'UPCA') }}
#else
{{ DNS1D::getBarcodeHTML($item['sku'], 'EAN13') }}
#endif
<div class="sku">{{ $item['sku'] }}</div>
</div>
<?php $i++; ?>
#else
<div style="clear: both"></div>
<?php $i = 1; ?>
#endif
#endforeach
This my ajax post
$('#barcode').click(function() {
var rows_selected = $('#dt-produk').DataTable().column(12).checkboxes.selected();
var id = [];
$.each(rows_selected, function(index, rowId) {
id.push(rowId);
});
var datax = JSON.stringify(id);
$.ajax({
url: "{{ route('cetakBarcode.produk') }}",
type: "post",
data: {
id: datax
},
xhrFields: {
responseType: 'blob'
},
success: function(response) {
var blob = new Blob([response]);
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "barcode-produk.pdf";
link.click();
},
error: function(blob) {
console.log(blob);
}
})
});
This is the controller
function cetakBarcode(Request $req)
{
$ids = json_decode(stripslashes($req->id));
$datax = [];
foreach ($ids as $id) {
$produk = DB::table('produks')->where('id', $id)->first();
$datax[] = [
'nama' => $produk->nama,
'harga_jual' => $produk->harga_jual,
'sku' => $produk->sku
];
}
$datax = [
'title' => 'Label Produk',
'date' => date('m/d/Y'),
'produks' => $datax
];
$pdf = PDF::loadView('pages.master.produk.barcode', $datax);
$path = public_path('file/pdf');
$fileName = 'barcode-produk.' . 'pdf';
$pdf->save($path . '/' . $fileName);
$pdf = public_path('file/pdf/' . $fileName);
return response()->download($pdf);
}
The error is 500 (Internal Server Error)
So I've just ran a few tests using this library, It throws some exceptions if the values are not in the correct format, Since you are running this inside a blade view, You will have to use the #phpe.g.
#php
try {
if (strlen($item['sku']) == 12) {
echo DNS1D::getBarcodeHTML($item['sku'], 'UPCA');
} else {
echo DNS1D::getBarcodeHTML($item['sku'], 'EAN13');
}
} catch (\Milon\Barcode\WrongCheckDigitException $e) {
echo $e->getMessage();
}
#endphp
I'm creating a website and now I try to use my upload file system. I test it with postman and it works perfectly. But when I try to use with my website page, it not works.
Backend : I use Lumen
Frontend : I use Buefy
The upload function into UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\User;
use Illuminate\Support\Facades\DB;
class UserController extends Controller
{
public function uploadImageIntoUser(Request $request, $id){
//try{
$user = User::findOrFail($id);
if ($user->id == Auth::id()) {
$url = json_decode($this->uploadImage($request, $id)->getContent(), true);
$newRequest = new Request();
$newRequest->replace(['picture' => $url['data']['image'] ]);
return $this->update($id, $newRequest);
}
return response()->json(['message' => 'You not have the right to do this'], 412);
/*}catch (\Exception $e){
return response()->json(['message' => 'User not found'], 404);
}*/
}
}
The upload function into my Controller.php
<?php
namespace App\Http\Controllers;
use Laravel\Lumen\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Galerie;
use Illuminate\Support\Str;
class Controller extends BaseController
{
//Upload image
public function uploadImage(Request $request, $id)
{
try{
$this->validate($request, [
'folder' => array(
'required',
'alpha')
]);
$folder = $request->input('folder');
if(strcmp($folder, "user") !== 0 && strcmp($folder, "article") !== 0 && strcmp($folder, "galerie") !== 0){
return response()->json(['message' => 'Incorrect folder name : choose between user, article and galerie'], 409);
}
} catch (\Exception $e) {
return response()->json(['message' => 'Incorrect folder name : only in lowercase'], 409);
}
$response = null;
$user = (object) ['image' => ""];
if ($request->hasFile('image')) {
$original_filename = $request->file('image')->getClientOriginalName();
$original_filename_arr = explode('.', $original_filename);
$file_ext = end($original_filename_arr);
if($folder == 'user'){
$destination_path = './upload/user/';
}else if($folder == 'article'){
$destination_path = './upload/article/';
}else if($folder == 'galerie'){
$destination_path = './upload/galerie/';
}
$image = time() . '.' . $file_ext;
if ($request->file('image')->move($destination_path, $image)) {
if ($folder == 'user') {
$user->image = '/upload/user/' . $image;
}else if($folder == 'article'){
$user->image = 'upload/article/' . $image;
}else if($folder == 'galerie'){
$user->image = 'upload/galerie/' . $image;
$galerie = new Galerie;
$galerie->id = Str::uuid();
$galerie->url = $user->image;
$galerie->save();
}
return $this->responseRequestSuccess($user);
} else {
return $this->responseRequestError('Cannot upload file');
}
} else {
return $this->responseRequestError('File not found');
}
}
protected function responseRequestSuccess($ret)
{
return response()->json(['status' => 'success', 'data' => $ret], 200)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
protected function responseRequestError($message = 'Bad request', $statusCode = 200)
{
return response()->json(['status' => 'error', 'error' => $message], $statusCode)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
}
Call my upload system from my profile page (called connexion.vue)
<template>
<section class="section">
<div class="container">
<p id="center-text" class="title">Informations Personnelles</p><br>
<b-notification v-if="error" type="is-warning">
{{ error }}
</b-notification>
<div class="columns">
<div class="column">
<img :src='baseURL + loggedInUser.picture'>
<b-field label="Modifier la photo de profil">
<b-field class="file is-secondary" :class="{'has-name': !!file2}">
<b-upload v-model="file2" class="file-label" rounded>
<span class="file-cta">
<b-icon class="file-icon" icon="upload"></b-icon>
<span class="file-label"><strong>Sélectionner un fichier à envoyer</strong></span>
</span>
<span class="file-name" v-if="file2">
{{ file2.name }}
</span>
</b-upload>
</b-field>
</b-field>
<b-button v-if="file2" type="is-secondary" #click="upload">Envoyer</b-button>
</div>
<div class="column">
<p class="title">{{ loggedInUser.pseudo }} <b-button #click="modifyPseudo" icon-right="pencil"/> </p><br v-if="!isModifyPseudo">
<form v-if="isModifyPseudo" method="post" #submit.prevent="sendModification">
<b-field label="Nouveau nom d'utilisateur" label-for="newPseudo">
<b-input id="newPseudo" v-model="newPseudo"></b-input>
</b-field>
<div class="control">
<button type="submit" class="button is-secondary is-fullwidth">
<strong>Modifier</strong>
</button>
</div><br>
</form>
<p class="subtitle">Adresse mail : {{ loggedInUser.email }} <b-button #click="modifyMail" icon-right="pencil"/> </p>
<form v-if="isModifyMail" method="post" #submit.prevent="sendModification">
<b-field label="Nouvelle adresse mail" label-for="newMail">
<b-input id="newMail" v-model="newMail" type="email"></b-input>
</b-field>
<div class="control">
<button type="submit" class="button is-secondary is-fullwidth">
<strong>Modifier</strong>
</button>
</div><br>
</form>
<p class="subtitle">Nationalité : {{ loggedInUser.nationality }} <b-button #click="modifyNation" icon-right="pencil"/> </p>
<form v-if="isModifyNation" method="post" #submit.prevent="sendModification">
<b-field label="Nouvelle nationalité" label-for="newNation">
<b-select expanded v-model="newNation" icon="earth">
<option
v-for="nation in nationalities"
:value="nation.code"
:key="nation.id">
{{ nation.name }}
</option>
</b-select>
</b-field>
<div class="control">
<button type="submit" class="button is-secondary is-fullwidth">
<strong>Modifier</strong>
</button>
</div><br>
</form>
</div>
</div>
</div>
</section>
</template>
<script>
import { mapGetters } from 'vuex'
import countries from '#/assets/countries.json';
export default {
middleware: 'auth',
computed: {
...mapGetters(['isAuthenticated', 'loggedInUser'])
},
data (){
return {
baseURL: 'http://localhost:8000/',
isModifyPseudo: false,
isModifyMail: false,
isModifyNation: false,
newPseudo: '',
newMail: '',
newNation: '',
nationalities: {},
error: '',
file2 : null,
}
},
methods: {
modifyPseudo() {
if(!this.isModifyPseudo){
this.newPseudo='';
}
this.isModifyPseudo = !this.isModifyPseudo;
},
modifyMail() {
if(!this.isModifyMail){
this.newMail='';
}
this.isModifyMail = !this.isModifyMail;
},
modifyNation() {
if(!this.isModifyNation){
this.newNation='';
}
this.isModifyNation = !this.isModifyNation;
},
async upload(){
try{
var formData = new FormData();
console.log(this.file2);
formData.append('image', this.file2);
const newPicture = await this.$axios.post('users/' + this.loggedInUser.id + '/picture', formData, {
headers: {'Content-Type': 'multipart/form-data'}
});
console.log(newPicture);
const updatedUser = {...this.$auth.user}
updatedUser.picture = newPicture.data.picture;
this.$auth.setUser(updatedUser)
this.file2 = null;
}catch (error){
//this.error = error.response.data.message;
console.log(error.response);
}
},
async sendModification(){
try{
if(this.isModifyPseudo){
const newPseudo = await this.$axios.put('users/' + this.loggedInUser.id, {
pseudo: this.newPseudo
});
const updatedUser = {...this.$auth.user}
updatedUser.pseudo = newPseudo.data.pseudo;
this.$auth.setUser(updatedUser)
this.newPseudo = '';
this.isModifyPseudo = false;
}
if(this.isModifyMail){
const newMail = await this.$axios.put('users/' + this.loggedInUser.id, {
email: this.newMail
});
const updatedUser = {...this.$auth.user}
updatedUser.email = newMail.data.email;
this.$auth.setUser(updatedUser)
this.newMail = '';
this.isModifyMail = false;
}
if(this.isModifyNation){
const newNation = await this.$axios.put('users/' + this.loggedInUser.id, {
nationality: this.newNation
});
const updatedUser = {...this.$auth.user}
updatedUser.nationality = newNation.data.nationality;
this.$auth.setUser(updatedUser)
this.newNation = '';
this.isModifyNation = false;
}
}catch(error){
this.error = error.response.data.message;
}
}
},
async mounted() {
try {
this.nationalities = countries;
} catch (err) {
throw err;
}
},
}
</script>
<style scoped>
img {
border-radius: 50%;
object-fit: cover;
height: 10em;
width: 10em;
}
.container #center-text {
text-align: center;
}
.file-label strong{
color: white;
}
</style>
And when I click on the send button, because I don't catch the error, it sends the error 500.
EDIT :
So into my upload function into my profile page (called connexion.vue) :
I replace that
var formData = new FormData();
console.log(this.file2);
formData.append('image', this.file2);
by this
var formData = new FormData();
console.log(this.file2);
formData.append('image', this.file2);
formData.append('folder', 'user');
and into my Controller.php file I replace this :
if($folder == 'user'){
$destination_path = './upload/user/';
}else if($folder == 'article'){
$destination_path = './upload/article/';
}else if($folder == 'galerie'){
$destination_path = './upload/galerie/';
}
by this
if($folder == 'user'){
$destination_path = storage_path('../public/upload/user/');
//$destination_path = './upload/user/';
}else if($folder == 'article'){
$destination_path = storage_path('../public/upload/article/');
//$destination_path = './upload/article/';
}else if($folder == 'galerie'){
$destination_path = storage_path('../public/upload/galerie/');
//$destination_path = './upload/galerie/';
}
I was searching online all day today and could not find any solution for adding a dynamic image to owl carousel from MySQL database with information. If anyone can help?
I have done something like the following but I am getting only one slide, Like bootstrap, it is not showing all the images and table information from the database. If I loop it gives me all the tables on the same page.
<link rel="stylesheet" type="text/css" href="http://www.24limousine.com/wp-content/themes/24Limousine/assets/css/owl.carousel.min.css">
<?php
$connect = mysqli_connect("localhost", "root", "", "testing");
function make_query($connect)
{
$query = "SELECT * FROM banner ORDER BY banner_id ASC";
$result = mysqli_query($connect, $query);
return $result;
}
function make_slide_indicators($connect)
{
$output = '';
$count = 0;
$result = make_query($connect);
while($row = mysqli_fetch_array($result))
{
if($count == 0)
{
$output .= '
<li data-target="#dynamic_slide_show" data-slide-to="'.$count.'" class="active"></li>
';
}
else
{
$output .= '
<li data-target="#dynamic_slide_show" data-slide-to="'.$count.'"></li>
';
}
$count = $count + 1;
}
return $output;
}
return $output;
}
function make_slides($connect)
{
$output = '';
$count = 0;
$result = make_query($connect);
while($row = mysqli_fetch_array($result))
{
if($count == 0)
{
$output .= '<div class="item active">';
}
else
{
$output .= '<div class="item">';
}
$output .= '
<img src="banner/'.$row["banner_image"].'" alt="'.$row["banner_title"].'" />
<div class="carousel-caption">
<h3>'.$row["banner_title"].'</h3>
</div>
</div>
';
$count = $count + 2;
}
return $output;
}
?>
<div class="cover-wrapper">
<div id="client-logos" class="owl-carousel text-center">
<div class="item">
<div class="client-inners">
<?php echo make_slides($connect); ?>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="http://www.24limousine.com/wp-content/themes/24Limousine/assets/js/owl.carousel.min.js"></script>
<script>
$(document).ready(function() {
$('#client-logos').owlCarousel({
// loop:true,
margin:15,
nav:true,
responsive:{
0:{
items:2
},
600:{
items:4
},
1000:{
items:6
}
},
navText: ["<img src='http://pixsector.com/cache/a8009c95/av8a49a4f81c3318dc69d.png'/>","<img src='http://pixsector.com/cache/81183b13/avcc910c4ee5888b858fe.png'/>"]
});
I want to save compressed image in laravel upload. I have found a package called "intervention/image". But it has resize functionality not compress.
You can simply make this:
public function compress($source, $destination, $quality = 75) {
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg') {
$image = imagecreatefromjpeg($source);
} elseif ($info['mime'] == 'image/gif') {
$image = imagecreatefromgif($source);
} elseif ($info['mime'] == 'image/png') {
$image = imagecreatefrompng($source);
}
imagejpeg($image, $destination, $quality);
return $destination;
}
The destination can be same the source
<form action="{{route('resizeImagePost')}}" method="POST" enctype="multipart/form-data">
#csrf
<div class="row">
<div class="col-md-12">
<br/>
<input type="file" name="image" placeholder="image" class ="image">
</div>
<div class="col-md-12">
<br/>
<button type="submit" class="btn btn-success">Upload Image</button>
</div>
</div>
</form>
public function resizeImagePost(Request $request)
{
$this->validate($request, [
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$image = $request->file('image');
$upload_imagename = time().'.'.$image->getClientOriginalExtension();
$upload_url = public_path('/images').'/'.$upload_imagename;
$filename = $this->compress_image($_FILES["image"]["tmp_name"], $upload_url, 40);
return back()
->with('success','Image Upload successful');
}
public function compress_image($source_url, $destination_url, $quality) {
$info = getimagesize($source_url);
if ($info['mime'] == 'image/jpeg')
$image = imagecreatefromjpeg($source_url);
elseif ($info['mime'] == 'image/gif')
$image = imagecreatefromgif($source_url);
elseif ($info['mime'] == 'image/png')
$image = imagecreatefrompng($source_url);
imagejpeg($image, $destination_url, $quality);
return $destination_url;
}
I searched a lot but couldn't find an answer to my problem. The set_value() function is not working on the GET form method whereas it is working on POST. I am trying to get the rows from MySQL and I want to use the GET method for this. Can anyone help, please?
view:
<?=form_open('employee_registration/search_employee', ['role'=>'form','method'=>'GET']);?>
<div class="row">
<div class="col-sm-3">
<div class="form-group">
<label>R. No.<span class="required">*</span></label>
<input class="form-control" placeholder="R. No." name="srch_r_no" id="srch_r_no" value="<?=set_value('srch_r_no');?>">
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
<label>Name<span class="required">*</span></label>
<input class="form-control" placeholder="Name" name="srch_e_name" id="srch_e_name" value="<?=set_value('srch_e_name');?>">
</div>
</div>
</div>
<button type="submit" class="btn btn-primary" name="srch_btn">Search <span class="fa fa-search"></span></button>
<?=form_close();?>
Controller:
public function search_employee()
{
$get = $this->input->get();
unset($get['srch_btn']);
$table = $this->md_emp_reg->search_employee($get);
$this->index('view',$table);
}
model:
public function search_employee($get)
{
$parameters = $this->filter_values($get,"search");
$query = "CALL `sp_select_employee_details`(".$parameters.");";
$grid = $this->table($query);
return $grid;
}
public function filter_values($arr,$type)
{
$arr_keys = array_keys($arr);
$filtered_values = "";
for ($i=0; $i < count($arr); $i++)
{
if ($arr[$arr_keys[$i]] == "" && $type == "search")
{
$arr[$arr_keys[$i]] = "";
}
elseif($arr[$arr_keys[$i]] == "" && $type != "search")
{
$arr[$arr_keys[$i]] = NULL;
}
$filtered_values .= $this->db->escape($arr[$arr_keys[$i]]).",";
}
return rtrim($filtered_values,',');
}
public function table($query)
{
$result = $this->db->query($query);
$r_arr = $result->result_array();
$result_fields_name = $result->list_fields();
$result_num_fields = $result->num_fields();
$result_num_rows = $result->num_rows();
$table = '<table width="100%" class="table table-condensed table-striped table-bordered table-hover" id="dataTables-example"><thead><tr>';
for ($a=0; $a < $result_num_fields; $a++)
{
$table .= "<th>".$result_fields_name[$a]."</th>";
}
$table .="</tr></thead><tbody>";
for ($i=0; $i < count($r_arr) ; $i++)
{
$table .= "<tr>";
for ($j=0; $j < $result_num_fields ; $j++)
{
$table .= "<td>".$r_arr[$i][$result_fields_name[$j]]."</td>";
}
$table .= "</tr>";
}
$table .="</tbody></table>";
$this->db->close();
return $table;
}
Here is the function:
function set_value($field, $default = '', $html_escape = TRUE)
{
$CI =& get_instance();
$value = (isset($CI->form_validation) && is_object($CI->form_validation) && $CI->form_validation->has_rule($field))
? $CI->form_validation->set_value($field, $default)
: $CI->input->post($field, FALSE);
isset($value) OR $value = $default;
return ($html_escape) ? html_escape($value) : $value;
}
Removing the form_validation logic as it isn't useful to us we get:
function set_value($field, $default = '', $html_escape = TRUE)
{
$CI =& get_instance();
$value = $CI->input->post($field, FALSE);
isset($value) OR $value = $default;
return ($html_escape) ? html_escape($value) : $value;
}
Exchanging for post we can create our own helper set_value_get(), save it in a helper, load the helper .etc.:
function set_value_get($field, $default = '', $html_escape = TRUE)
{
$CI =& get_instance();
$value = $CI->input->get($field, FALSE);
isset($value) OR $value = $default;
return ($html_escape) ? html_escape($value) : $value;
}
Usage would be the same as set_value.