Session in laravel - laravel

class ControlController extends Controller
{
public function anyadirCarrito($id, $quan) {
$productoCarrito = (object)array(
'id' =>$id,
'cantidad' => $quan,
);
\Session::push('cart', $productoCarrito);
return \Session::get('cart');
}
}
I'm trying to call this function to store data, but every time I call it, it overwrites the data, I want it to store it next to the other one, but it overwrites it. How can I store it with the other one? And if I give him an id, how can I erase it?

The Laravel Session operates on a key/value basis. Therefore, when you push another item to the key cart, you are overwriting the same key to which you pushed the previous value.
If you want to maintain a cart, with all the products you've added, you'd first need to retrieve the value, and append the new product. For example:
public function addProduct($id, $quantity) {
// Get cart from session
$cart = session('cart', []);
// Increment existing product quantity, or add product to cart
if (array_key_exists($id, $cart)) {
$cart[$id]->quantity += $quantity;
} else {
$cart[$id] = (object) compact('id', 'quantity');
}
// Set cart in session
session(compact('cart'));
return $cart;
}
public function removeProduct($id) {
// Get cart from session
$cart = session('cart', []);
// Remove product from cart
unset($cart[$id]);
// Set cart in session
session(compact('cart'));
return $cart;
}

Related

how to hide id from url in Laravel 6?

hide id from url
https://wallpaperaccess.in/photo/162/download-wallpaper
i want url like this
https://wallpaperaccess.in/photo/download-wallpaper
ImagesController.php
public function show($id, $slug = null ) {
$response = Images::findOrFail($id);
$uri = $this->request->path();
if( str_slug( $response->title ) == '' ) {
$slugUrl = '';
} else {
$slugUrl = '/'.str_slug( $response->title );
}
$url_image = 'photo/'.$response->id.$slugUrl;
//<<<-- * Redirect the user real page * -->>>
$uriImage = $this->request->path();
$uriCanonical = $url_image;
if( $uriImage != $uriCanonical ) {
return redirect($uriCanonical);
}
Route
// Photo Details
Route::get('photo/{id}/{slug?}','ImagesController#show');
NOTE: i don't have any slug column in database, so can we use title as slug?
You should add a column field slug and auto-generate it from title
use Illuminate\Support\Str;
$slug = Str::slug($request->input('title'), '-');
In Models\Image.php
public function getRouteKeyName()
{
return 'slug';
}
In routes\web.php
Route::get('photo/{image:slug}','ImagesController#show');
In app\Http\Controllers\ImagesController.php
use app\Models\Image.php;
...
public function show(Image $image)
{
// controller will automatically find $image with slug in url
// $image_id = $image->id;
return view('your.view', ['image' => $image]);
}
In order to use a slug in the URL instead of an id, you'll need to...
Create a column in your table where you store the slug. A good way to make a slug unique is to append the actual id at the end. If you really don't want to see the id anywhere, you have no choice, you'll have to ensure the slug is unique yourself (there are a lot of ways to achieve this).
This is one way to automatically create an unique slug:
Make sure the slug column is nullable, then open your model and add these methods.
They are called "model events".
created is called when the model is, well, created.
updating is called when you are updating the model but before it's actually updated.
Using created and updating should automatically create the slug when you create or update a Images instance.
protected static function booted()
{
parent::booted();
static::created(function (Images $images) {
$images->slug = Str::slug($images->title.'-'.$images->id);
$images->save();
});
static::updating(function (Images $images) {
$images->slug = Str::slug($images->title.'-'.$images->id);
});
}
From a SEO point of view, updating the slug when the title change is arguably not a good practice, so you might want to omit this part (static::updating...), it's up to you.
Go to your model and add the following method:
/**
* Get the route key for the model.
*
* #return string
*/
public function getRouteKeyName()
{
return 'slug'; //or whatever you call the slug column
}
This way, the router will resolve your model by the slug, not the id.
In your route file, remove the id and change the name of the slug to match the name of your model:
Route::get('photo/{images}','ImagesController#show'); //here I'm assuming your model is Images from what I see in your controller
In your controller, change the declaration of your show method to this:
public function show(Images $images)
{
dd($images);
// if you did all this correctly, $images should be the Images corresponding to the slug in the url.
// if you did something wrong, $images will be an empty Images instance
//
//
// your code...
}
Images should be renamed to Image, models should not be plural. However, it should not make any difference here.

Laravel 4.2 Page Views Counter

So i added this page view counter to my app that counts each visit on a artist page. Right now if you refresh the page the counter is +1 each refresh.
My question is how can i make it to count unique visits by day only?
My Controller:
if ( $artist ) {
$getartist = $this->_artist->get($artist, 'slug');
if ( $getartist ) {
$getsongs = $this->_song->collections($input, $getartist->id, 'ASC');
$this->_artist->updateVisits($getartist->id);
$data = [
'is_artist' => true,
'artist' => $getartist,
'songs' => $getsongs,
'randomsongs' => $this->randomsongs,
];
return $this->view('index', $data);
}
}
The code for counter is:
$this->_artist->updateVisits($getartist->id);
Then in my ArtistRepository:
public function updateVisits($artist_id)
{
$artist = $this->model->where("id",$artist_id)->first();
$artist->visits = $artist->visits+1;
$artist->save();
}
So how do i prevent counter from counting if user refresh the page?
Ok i found a solution around this with cookies
Heres my code.
public function updateVisits($artist_id)
{
$artist = $this->model->where("id",$artist_id)->first();
// Check if cookies exist
if(!isset($_COOKIE['visited_id' . $artist_id])) {
// If not set cookie and pass counter
setcookie('visited_id' . $artist_id, $artist_id, time()+30); /* expire in seconds */
$artist->visits = $artist->visits+1;
$artist->save();
// If cookie exist on user computer
} else {
//do nothing
}
}
First add a date field on DB table. Then change your function to following-
public function updateVisits($artist_id)
{
$artist = $this->model->firstOrCreate(['id' => $artist_id,'your_date_field_name'=>date('Y-m-d')]);
$artist->visits = $artist->visits+1;
$artist->save();
}
And don't forget to add id, your_date_field_name on fillable array to be mass assignable.

magento clear cache programatically for a particular product using product id

As my question says I want to remove cache (FULL PAGE CACHE) for a particular product using product id. Is that possible ?
Every model has cleanModelCache() method that clean the cache using the model tags.
See Mage_Catalog_Model_Product::cleanModelCache()
public function cleanModelCache()
{
$tags = $this->getCacheIdTagsWithCategories();
if ($tags !== false) {
Mage::app()->cleanCache($tags);
}
return $this;
}
Mage::app()->cleanCache($tags); is what cleans the cache.
If you want to clean using only the product ID you'll need to load at least the categories associated to that product and built the cacha tag list as for the method Mage_Catalog_Model_Product::getCacheIdTagsWithCategories()
public function getCacheIdTagsWithCategories()
{
$tags = $this->getCacheTags();
$affectedCategoryIds = $this->_getResource()->getCategoryIdsWithAnchors($this);
foreach ($affectedCategoryIds as $categoryId) {
$tags[] = Mage_Catalog_Model_Category::CACHE_TAG.'_'.$categoryId;
}
return $tags;
}

Add associated products to quote but not cart

I have created a new product type in Magento. However, I am having difficulty adding all of its associated products to the sales_flat_quote_item table. I only want the associated products added to the table and only the main parent product visible in the cart.
I am real close to achieving this. Right now only the parent item is visible in the cart when adding it to the cart. However, only one of it's associated products are being listed in the above mentioned table.
Here is a snippet of my code:
class Namespace_Module_Model_Product_Type_Custom extends Mage_Catalog_Model_Product_Type_Abstract {
........
protected function _prepareProduct(Varien_Object $buyRequest, $product, $processMode)
{
$qty = $buyRequest['qty'];
$associatedQty = $buyRequest['associated_qty'];
if($qty >= 1) {
$result = parent::_prepareProduct($buyRequest, $product, $processMode);
if (is_array($result)) {
$product = $this->getProduct($product);
foreach($buyRequest['associated'] as $associated){
if($associated){
$subProducts[] = Mage::getModel('catalog/product')->load($associated);
}
}
foreach($subProducts as $subProduct){
if($subProduct){
$product->setCartQty($qty);
$product->addCustomOption('product_qty_'.$subProduct->getId(), $associatedQty[$subProduct->getId()], $subProduct);
$product->addCustomOption('associated_product_' . $subProduct->getId(), $associatedQty[$subProduct->getId()]);
}
}
$_result = $subProduct->getTypeInstance(true)->_prepareProduct(
$buyRequest,
$subProduct,
$processMode
);
if (!isset($_result[0])) {
return Mage::helper('checkout')->__('Cannot add the item to shopping cart');
}
$_result[0]->setParentProductId($product->getId())
->addCustomOption('parent_product_id', $product->getId());
$result[] = $_result[0];
return $result;
} else {
return $this->getSpecifyOptionMessage();
}
} else {
return $this->getQtyMessage();
}
}
........
}
Right now only the associated product '53' is being added as a child product. I am still missing the other two. Basically, the foreach($subProducts as $subProduct) loop will loop 3 three times with the three associated products. I am assuming somewhere along the lines in Magento it is only using the last looped product.
Any advice or help with this would be great. Thanks in advance!
Got it figured out. I just had to shift the following into the foreach loop instead of outside of it.
$_result[0]->setParentProductId($product->getId())
->addCustomOption('parent_product_id', $product->getId());
$result[] = $_result[0];

Updating customer data from observer after customer_register_success event

Having issues setting the customers group id from an observer. The event is picking up on a new user creation via customer_register_success event. The event is passed to my observer, e.g.
public function registrationSuccess(Varien_Event_Observer $observer) {
// extract customer data from event
$customer = $observer->getCustomer()->getData();
Mage::log('COOKIES', json_encode($_COOKIE));
// a cookie should have been set with the membership id
if (isset($_COOKIE['membership_account_id'])) {
Mage::log('COOKIE SET, ASSOCIATING MEMBERSHIP');
// associate new account with membership, and upgrade user to membership status
$this->associateMembership($customer['entity_id'], $_COOKIE['membership_account_id']);
}
}
Which then calls the associateMembership method to update the group id, and set a custom customer attribute called rms_id:
public function associateMembership($customer_id, $account_id) {
// load customer model
$customer = Mage::getModel('customer/customer')->load($customer_id);
Mage::log('CUSTOMER DATA: ' . json_encode($customer->toArray()));
// upgrade customer to membership level, and set custom rms_id attribute
$customer
->setWebsiteId(Mage::app()->getWebsite()->getId())
->setGroupId(4)
->setRmsId($account_id);
// save
try {
$customer->save();
Mage::log('ACCOUNT ASSOCIATED: CUSTOMER ID = ' . $customer_id . ' ACCOUNT ID = ' . $account_id);
} catch (Exception $ex) {
Mage::log($ex);
}
}
For some reason, there's no error coming back. I'm getting the correct user id, and everything seems to be working. However, the group is not being set, nor is my custom id.
Should I be using another event that will allow the save to go through?
Try loading the website id before loading the customer
$customer = Mage::getModel('customer/customer')
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->load($customer_id);
customer_register_success will re-save the customer data after you save it in your custom observer
Also customer_register_success pass the customer data so you should not need to reload it.
see /app/code/core/Mage/Customer/controllers/AccountController.php
Mage::dispatchEvent('customer_register_success',
array('account_controller' => $this, 'customer' => $customer)
);
Try
public function registrationSuccess(Varien_Event_Observer $observer) {
// extract customer data from event
$customer = $observer->getCustomer();
Mage::log('COOKIES', json_encode($_COOKIE));
// a cookie should have been set with the membership id
if ($membership_account_id = Mage::getModel('core/cookie')->get('membership_account_id')) {
Mage::log('COOKIE SET, ASSOCIATING MEMBERSHIP');
$customer->setGroupId(4)
->setRmsId($membership_account_id);
}
return $this;
}
Try to set customer website id before load.
e.g.
$customer = Mage::getModel('customer/customer')
->setWebsiteId(Mage::app()->getWebsite()->getId())
->load($customer_id);
Also try to put die; after $customer->save(); while testing - in such case you will be sure that nothing else changes customers data after you (may be some other observer).

Resources