so I have a code that shows all my product
#foreach($products as $product)
<div class="col-lg-4 col-md-4 col-sm-6 col-12 event-item-col ">
<div class="card card-event info-overlay">
<div class="img has-background h-50">
<div class="pop-info ">
<span class="event-badges ">
<span class="badge price-tag big badge-default">{{$product->price}}</span>
</span>
</div>
<a href="/product/{{$product->id}}" class="event-pop-link">
<span class="event-badges ">
<span class="badge badge-danger"> if he buy</span>
</span>
<div class="event-pop-info">
<p class="badge">{{$product->price}}</p>
<p class="publisher">by <strong><?php $id = $product->user_id; $users = $user->findOrFail($id); echo $users->first; ?> <?php echo $user->last ?></strong></p>
</div>
</a>
<a href="event-details.html">
<img alt="340x230" class="card-img-top img-responsive h-100" data-holder-rendered="true" src="image/products/product{{$product->id}}.jpg"> </a>
</div>
<div class="card-body h-50">
<h4 class="card-title">
{{$product->pname}}
</h4>
<p class="card-tex" style="overflow: hidden">{{$product->smalldescription}}</p>
<div class="card-event-info">
<p class="event-location"><i class="fas fa-location-arrow"></i>
<a class="location" href="/user/product/{{$id}}"><?php echo $users->first; ?> <?php echo $user->last ?></a></p>
<p class="event-time"><i class="fas fa-calendar-alt"> {{$product->created_at->format('m/d/Y')}}</i></p>
</div>
</div>
</div>
</div>
#endforeach
and this is my controller
public function index()
{
$user = User::find(1);
$products = product::orderBy('created_at', 'desc')->Paginate($perPage = 15, $columns = ['*'], $pageName = 'page', $page = null);
return view('welcome', compact('products', 'user'));
}
like you can see in my view I have this code
<?php $id = $product->user_id; $users = $user->findOrFail($id); echo $users->first; ?> <?php echo $user->last ?>
that makes me able to get the name of the user that create this product, product and user table has one too many relations.i want to change this code to a better and smaller code.
product->user->first
don't work.
I tried it so many ways but that just doesn't work.
if anyone can help me to get data with laravel way I will be grateful. (sry if my question is duplicate, I tried so many ways but didn't work )
to give u guys more info this is my class
class User extends Authenticatable
{
use Notifiable;
use Friendable;
protected $fillable = [
'first','last', 'email', 'password','phone','question','answer','description',
];
protected $hidden = [
'password', 'remember_token',
];
public function products()
{
return $this->hasMany(Product::class);
}
}
and product class :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
the class product extends Model
{
protected $fillable = [
'part_id', 'smalldescription', 'description', 'pname', 'link', 'price',
];
public function users()
{
return $this->belongsTo(User::class);
}
}
Firstly I would like to point you out that you have already defined the relation in your product model you could use that to access the related user by calling the function. I would also like to suggest you to change the function name in your product model from users to user as belongsTo returns only single instance of the related model.
public function user()
{
return $this->belongsTo(User::class);
}
Coming back to your query when querying products use with load a relation like in your case it would be.
product::with('user')->orderBy('created_at', 'desc')->Paginate($perPage = 15, $columns = ['*'], $pageName = 'page', $page = null);
Then inside your foreach loop on blade get user's name calling user function on $product like:
$product->user->name
I would also suggest to go through the laravel documentation about eloquent relations again.
Querying a relation
Related
I have a custom post type called "team-member" which is in relationship (using ACF) with another custom post type called "speciality".
I have wrote the code to display team member on the page, team member name and speciality and all works perfect.
All the team members have also own description, so I would like to display the team member title, description and speciality within the Popup.
This is the code I have so far:
$relatedTeamMembers = new WP_Query(array(
'posts_per_page' => -1,
'post_type' => 'team-member',
'orderby' => 'title',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'related_team_group',
'compare' => 'LIKE',
'value' => '130'
)
)
));
if ($relatedTeamMembers->have_posts()) {
echo '<div class="team-members wrapper wrapper--larger">';
echo '<h2>OUR DENTISTS</h2>';
echo '<div class="team-members__wrapper">';
while($relatedTeamMembers->have_posts()) {
$relatedTeamMembers->the_post(); ?>
<div class="team-member">
<a href="<?php the_permalink(); ?>" target="_blank">
<img class="team-member__image" src="<?php
if (has_post_thumbnail()) {
the_post_thumbnail_url('teamMemberPortrait');
} else {
echo get_theme_file_uri('img/placeholder.png');
} ?> ">
</a>
<div class="team-member__label-gold">
<div class="team-member__label-gold__name"><?php the_title(); ?></div>
<div class="white-underline-strip-h-thin"></div>
<div class="team-member__label-gold__speciality"><?php
$specialities = get_field('related_speciality');
foreach($specialities as $specialities);
echo $specialities->post_title; ?>
</div>
</div>
</div>
<?php }
echo '</div>';
echo '</div>';
}
wp_reset_postdata();
So looking at this pice <a href="<?php the_permalink(); ?>" target="_blank"> the target attribute behaves similarly, when the team member card is clicked it loads the data in the new window, I would like the same behaviour but instead the data need to be loaded within the popup.
My popup is done in JS and is using injectHTML() function as below:
injectHTML() {
document.body.insertAdjacentHTML('beforeend', `
<div>Team Member Details</div>
`)
}
But it I have no idea how to connect click event on the card member with the team member content.
I would be super grateful for a hint or correct way to achieve this type functionality?
bind() can pass event when call injectHTML(). Then in injectHTML(), the member info can pass.
As primary these can be use:
Add EventListener() with as, document.querySelector("a").addEventListener('click',injectHTML.bind(event));
Then, parse the required information by event.
Sorry for my English
I'am newbe in Codeigniter 4. I try to decrypt data from encrypted post request. I'm succeed encrypted my data in views, but can't to decrypting back again in my controller after post it with javascript. Here my code
My Controller
<?php namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\Store_MDL;
class Home extends BaseController
{
protected $ProductModel;
protected $request;protected $session;protected $encrypt;
public function __construct() {
$this->ProductModel = new Store_MDL();
$this->request = \Config\Services::request();
$this->encrypt = \Config\Services::encrypter();
$this->session = \Config\Services::session();
$this->session->start();
}
public function index()
{
$data['encrypter'] = $this->encrypt;
return view('home_page', $data);
}
public function encthis()
{
$val = $_POST['str'];
$encrypters = $this->encrypt;
//$ciphertext = $encrypters->encrypt('My secret message');
echo $encrypters->decrypt($val);
//echo $val;
return view('product/product-v');
}
}
here my views home_page.php
<?php $n=0; foreach ($product as $rows){
$n++;
//echo count($rows);
if($n < count($rows)){
$dev = '<div class="divider mb-3 mt-n2"></div>';
}else{$dev = '';}
if($n % 2 == 0){
echo '<a href="#" value = "'.base_url().'/home/encthis" data-v="'.$encrypter->encrypt($rows['prno']).'" class = "n-link"><div class="row">
<div class="col-6">
<h1 class="font-20 mb-0 line-height-l">'.$rows['prname'].'</h1>
<p class="mb-3">
'.$rows['prdescription'].'
</p>
<h2 class="font-16 mb-0">Rp. '.$rows['prprice'].'</h2>
</div>
<div class="col-6">
<img src="'.base_url().'/public/uploads/'.$rows['prpath'].'/'.$rows['primage'].'" class="img-fluid rounded-circle shadow-xl">
</div>
</div></a>'.$dev;
}else{
echo '<a href="#" value = "'.base_url().'/home/encthis" data-v="'.$encrypter->encrypt($rows['prno']).'" class = "n-link"><div class="row">
<div class="col-6">
<img src="'.base_url().'/public/uploads/'.$rows['prpath'].'/'.$rows['primage'].'" class="img-fluid rounded-circle shadow-xl">
</div>
<div class="col-6">
<h1 class="font-18 mb-0 line-height-l">'.$rows['prname'].'</h1>
<p class="mb-3">
'.$rows['prdescription'].'
</p>
<h2 class="font-16 mb-0">Rp. '.$rows['prprice'].'</h2>
</div>
</div></a>'.$dev;
}
} ?>
than here my script
<script>
$('.n-link').on('click', function () {
var link = $(this).attr('value');
var pos = $(this).attr('data-v');
$.post(link, { str:pos})
.done(function(data) {
document.getElementById("context").innerHTML = data;
});
});
</script>
I always get notification 500 (Internal Server Error).
After struggling hours, i find some clue,
just change
$encrypter->encrypt($rows['prno']);
with base64_encode($encrypter->encrypt($rows['prno']));
and in controller,
change
$encrypters->decrypt($val);
with $encrypters->decrypt(base64_decode($val));
Hope its useful
so I have a Wordpress page where I want to fetch the data... so I am using javascript ajax to get data from a PHP file... which is totally custom build... I want to run a shortcode of WordPress in this custom file and send the HTML of shortcode to the WordPress page...
here's the javascript
<script>
jQuery(document).ready(function(){
showjob();
});
function showjob() {
var intrest=document.getElementById("intrest").value;
jQuery.ajax({
method: 'GET',
url: 'jobsloader.php',
data: {
intrest: intrest,
type: 'need'
},
success: function(data)
{
document.getElementById("addcontainer").innerHTML = data;
}
});
}
</script>
here's the custom file code:
<?php
if ($_GET)
{
?>
<div class="vc_row wpb_row vc_row-fluid">
<?php
$intrest=$_GET['intrest'];
$search = "SELECT * FROM `$database`.`$job` where intrest='employee' && poj='$intrest'";
$result = mysqli_query($con, $search);
while ($row = mysqli_fetch_array($result))
{
?>
=======================================================================
<div class="wpb_column vc_column_container vc_col-sm-3">
<div class="vc_column-inner ">
<div class="wpb_wrapper">
<div class="centered-box sc-image-centered-box">
<div class="sc-image sc-wrapbox sc-wrapbox-style-11 sc-wrapbox-position-centered" style="width: 100px;height: 100px;">
<div class="sc-wrapbox-inner"><img onclick="loaddetail(<?php echo $row['id']; ?>)" class="sc-wrapbox-element img-responsive img-circle" src="<?php echo "../cloud/ads/".$row['addpic'].".png"; ?>" alt=""></div>
</div>
</div>
<div class="wpb_text_column wpb_content_element ">
<div class="wpb_wrapper">
<p style="text-align: center;"><?php echo $row['name']; ?></p>
</div>
</div>
<div class="vc_btn3-container vc_btn3-center">
<button class="vc_general vc_btn3 vc_btn3-size-md vc_btn3-shape-rounded vc_btn3-style-modern vc_btn3-block vc_btn3-icon-left vc_btn3-color-grey"><i class="vc_btn3-icon fa fa-handshake-o"></i> Full Details</button>
</div>
</div>
</div>
</div>
======================================================================
So the whole above code is just the html part of the below shortcode... also this html doesnt work properly[css problems]... so i want to make the shortcode work here and then send the worked code to the wordpress page.... how to???
or if I can send the shortcode as a text and make it work in WordPress page... that will be ok too. but how to???
<?php echo do_shortcode("[sc_team style="horizontal" team="abc" columns="1"]"); ?>
<?php
}
?>
</div>
<?php
}
else
{
echo "Please Try Again Later.";
}
?>
sorry for bad explanation, for more details plz comment .... and dont downvote cause i didnt find any answer from other places... and i am stuck on it...
Make it a plugin, which is easy to do.
Create a folder named myplugin in wp-content/plugins in the folder put a file named myplugin.php (same as the folder). In that file put this
<?php
/*
* Plugin Name: MyPlugin
* Version: 1.00.00
* Plugin URI:
* Description: Some Description
* Author: Me
* Author URI:
* License: Copyright (c) 2018 Me. All rights reserved.
*/
if(!function_exists('myshortcode')){
function myshortcode($atts, $contents=''){
$atts = shortcode_atts( [
'post_id' => '',
]);
...
}
}
add_shortcode( 'myshortcode', 'myshortcode');
Then go to the plugin page, and enable it.
I have two tables , categories and product.Each category has id and name. Each product has id, name and category id. Now I want to load the data on each tab when a user click on specific category_id.so related product will be shown on each category tab. I have tried but couldn't get the solution.
Category Model:
class Category extends Model
{
public function products()
{
return $this->hasMany('App\Product');
}
}
Product Model:
class Product extends Model
{
public function category()
{
return $this->belongsTo('App\Category');
}
}
Here is my controllers:
public function gettestItem() {
$categories = Category::with('products')->get();
return view('products', compact('categories'));
}
Here is the view :
<div class="container">
<div id="content">
<ul id="tabs" class="nav nav-tabs" data-tabs="tabs">
#foreach ($categories as $category)
<li><a href="#{{$category->id}}" data-toggle="tab" >{{$category->name}}</a></li>
#endforeach
</ul>
<div id="my-tab-content" class="tab-content">
#foreach($categories as $category)
#foreach($category->products as $product)
<div class="tab-pane " id="{{$category->id}}">
{{$product->name}}
</div>
#endforeach
#endforeach
</div>
</div>
</div>
Here is the route:
Route::get('/testItem',[
'uses'=>'ItemController#gettestItem',
'as'=>'testItem'
]);
if anyone could help me solve the problem will be appreciated.
If you have defined your schema and relations properly then function should be as:
public function gettestItem() {
$categories = Category::with('products')->get();
return view('products', compact('categories'));
}
then you can access product of each category as:
foreach ($categories as $category) {
$category->product; // gives all products corresponding to $category
}
And also please read the Docs
Update
Your 2nd foreach should be as:
<div id="my-tab-content" class="tab-content">
#foreach($categories as $category)
<div class="tab-pane" id="{{$category->id}}">
#foreach($category->products as $product)
<div>
{{$product->name}}
</div>
#endforeach
</div>
#endforeach
</div>
You can also use following code to get only those categories which have corresponding products:
$categories = Category::has('products')->with('products')->get();
I am trying to create a nice gallery for an e-commerce. - all the current code is here
The front-end layout I got from here followed the tutorial and it worked like a charm.
Then to add the payment module I decided to add a floating div:
<?php foreach ($tes as $te): ?>
<div id="<?php echo $te['Product']['id'] ?>">
<div class="shop-actions">
<div class="list-group">
<span href="#" class="list-group-item active comprar-menu-button">
<?php echo __('<i class="fa fa-shopping-cart"></i> Carrito de Compras'); ?>
</span>
<span href="#" class="list-group-item comprar-menu">
<h3>Agregar al carrito</h3>
<?php echo $this->Form->create('Product', array('default' => false, 'inputDefaults' => array(
'div' => 'form-group',
'label' => false,
'wrapInput' => false,
'class' => 'form-control'))); ?>
<div class="row">
<div class="col-md-12">
<?php
echo $this->Form->input('cantidad', array(
'options' => array(
50 => "50gr",
100 => "100gr",
150 => "150gr",
200 => "200gr",
250 => "250gr",
500 => "500gr",
1000 => "1kg",
'mayoreo' => "mayoreo",
),
'empty' => '(Seleccionar)',
));
?>
</div>
<div class="col-md-12 mayoreo">
<div class="input-group">
<?php echo $this->Form->input('mayoreo', array('label' => '', 'type'=>'number')); ?>
<span class="input-group-addon">KG</span>
</div>
</div>
<div class="col-md-12 subtotal">
<div id="<?php echo $te['Product']['price']; ?>"><span>$0.00 MXN</span> </div>
</div>
<div class="col-md-12">
</br>
<?php echo $this->Form->submit('Agregar', array('div' => 'form-group','class' => 'btn btn-info col-md-12')); ?>
</div>
</div>
<?php echo $this->Form->end(); ?>
<hr />
<h4>Ademas en tu carrito</h4>
<ul>
<li>Lung Jing <span class="pull-right">200gr</span></li>
<li>Pu Erh <span class="pull-right">1kg</span></li>
<li>Lapsang Su shang <span class="pull-right">10kg</span></li>
</ul>
<span class="pull-right">Subtotal: $2,500.00 MXN</span>
</span>
</div>
</div>
[…]
</div>
<?php endforeach; ?>
<span class="loading"></span>
<span class="icon close-content"><i class="fa fa-times"></i></span>
Then I tried to add some jQuery to make the UX nice and smooth…
function formatCurrency(total) {
var neg = false;
if(total < 0) {
neg = true;
total = Math.abs(total);
}
return (neg ? "-$" : '$') + parseFloat(total, 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString();
}
$('.comprar-menu-button').click(function(){
$(this).next().slideToggle(function(){
if ($(this).is(':visible')){
$(this).css('display','inline-block');
}
});
});
$('.cantidad-te').change(function(){
var value, product, precio, cantidadEspecial;
value = $(this).val();
product = $(this).parent().parent();
precio = $(this).parent().parent().next().next().children();
cantidadEspecial =product.next();
if (value === 'mayoreo') {
cantidadEspecial.show();
precio.children().html('especifique cantidad');
}else{
cantidadEspecial.hide();
subtotal = precio.attr('id') * value;
precio.children().html(formatCurrency(subtotal) + ' MXN');
}
});
In theory it works, however it only works for the last element on my teas product.
Expected outcome
When clicking on any element it should:
show the div with the shopping cart
slideToggle should show the form to add product to shopping cart
When selecting an element from dropdown it should:
update with correct price
Current outcome
Only slideToggle() works for last element on my grid.
when changing values on dropdown list it does not make the changes specified.
Additional info
To see a live version of how the 3D grid works visit here (this is not the version am currently working with as I havent pushed the changes)
The code for live version is here
Page Source (HTML Outcome) - here as pointed out by #AlexAtNet
Thank you