When I click on my first record to delete from my application, I get method not found error but when I click on another record apart from first one it easily gets deleted.
What is the issue?
Below is the code for Delete:
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$video = Video::findOrFail($id);
$delete = $video->delete();
if ($delete){
return redirect()->back()->with('trueDelete','Data Not Deleted');
}else{
return redirect()->back()->with('falseDelete','Data Deleted Successfully');
}
}
While clicking on first record from list shows below error,
Route::get('delete-video/{id}','VideoController#destroy');
First of all, that is too much work you are putting into deleting the record. Check out the link below on the official docs to see how to delete in a single line.
https://laravel.com/docs/5.6/eloquent#deleting-models
As for the image, you have a
Method not allowed exception.
This means that, on the place you are deleting from link one, you are using a different route variable than the one specified in the web.php file. Check that you aren't confusing a GET and POST and/or PUT.
Related
I'm working on a media asset management system. I want the user to be able to fill out a form with file width, height, extension and colorspace, then transform the image and serve it back as a download.
I can get that to work by responding to the Post-Request with the URL of the newly created file.
What I want is for that file to be deleted after download or after some time.
(Or, preferably, a way to use laravels download() Response, which I apparently can't use inside an Axios/Ajax post request).
Thanks for your help :)
There are two ways you can do this.
Let's assume you have a file in storage/app/download.zip:
1. Because Laravel uses Symfony's HttpFoundation internally, you can use the deleteFileAfterSend method:
public function download()
{
return response()
->download(storage_path('app/download.zip'))
->deleteFileAfterSend(true);
}
2. Create a Terminable Middleware that deletes the file after the download response was prepared.
class StorageDownload
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
return $next($request);
}
public function terminate($request, $response)
{
\Storage::delete('download.zip');
}
}
You'll need to register the middlware and assign it to your route for it to work.
As for triggering the download using JavaScript, something as trivial as setting the window location will work:
axios
.post('files/export/' + file.id, formData)
.then(function() {
window.location = 'files/download/' + file.id
});
Don't worry, this will not navigate away from your current page, it will just trigger the download.
for me , i like to handle this case using cron
you can read details here
add any column to check it's been downloaded or not (e.g status with value 0 or 1)
and you can create accessor on your model to count the date diff
public function getRangeDateAttribute(){
$today = Carbon::now()->startOfDay();
$downloadDate = $this->created_at;
$datediff = $today->diffInDays($downloadDate);
return $datediff
}
then sample code inside task scheduling :
if($media->status == 1 || $media->rangeDate > 7 ){ //checking the status & range date passed specific days you wanted
do whatever you wanted here
}
I'm converting a Laravel app that was using Backpack across to Laravel Nova.
One of my models Images allows the user to add multiple images with a base set of information from the initial form. The form in this instance asks how many images are in the series via a dropdown and then has a number of relevant fields that will be used for all of the new images being added. When saving, in the controller, I'm using the following eloquent feature to run a number of tasks and insert the required number of rows:
public function store(StoreRequest $request){
//Get some info
//Make some tweaks
//Use for loop to save multiple records
for ($k = 0; $k < $addim; $k++){
//Do some stuff
parent::storeCrud(${"request"});
}
}
This works perfectly and inserts however many records are required.
In Laravel Nova, I can't see a way to use this same approach. Using an event listener in the model doesn't seem like the right way to save multiple records and I can't find any reference to a controller function I can use to achieve this.
I would really appreciate some thoughts and guidance on the best way to complete this part.
If someone has stumbled upon this type of problem.
You can use Laravel Observers.
In order to restrict the event to be fired only when resource is created and only using nova you can declare Observer in NovaServiceProvider.php as follows
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
parent::boot();
Nova::serving(function () {
Image::observe(ImageObserver::class);
});
}
Above code will only be triggered when your image object is modified using nova system only.
For ref Observer code will look like following
<?php
namespace App\Observers;
use App\Models\Document;
class ImageObserver
{
/**
* Handle the Image "created" event.
*
* #param \App\Models\Image $image
* #return void
*/
public function created(Image $image)
{
//logic to create multiple records
}
}
You can use the saving event in an observable
https://laravel.com/docs/5.8/eloquent#events
I have create a observer, before edit button click event are occurred.
using this I could change the value of select box
For an observer to be called, two things should exist, an event and an $observer which listens to that event. To set an observer on an event simply google, you will find out how.
If you wanna debug your observer,there are two important methods you can watch to understand what's going on. The first one is Mage_Core_Model_App#dispatchEvent at app/code/core/Mage/Core/Model/App.php:1271
public function dispatchEvent($eventName, $args)
{
$eventName = strtolower($eventName);
foreach ($this->_events as $area=>$events) {
// (...)
This is where all events has a stop on their way. During development, you can inspect the $eventName by setting a breakpoint here (my favorite), logging the value to a file, or even get very dirty and simply echo to see under the hood.
public function dispatchEvent($eventName, $args)
echo "BlaBlaBla"; // just used to find the printed lines in view source code of browser
print_r($eventName);
$eventName = strtolower($eventName);
foreach ($this->_events as $area=>$events) {
// (...)
Remember, you are editing core files, and this is just to explore and find the event name, get rid of these lines afterwards.
The second method which actually does the job is Mage_Core_Model_App#_callObserverMethod at app/code/core/Mage/Core/Model/App.php:1338
/**
* #param object $object
* #param string $method
* #param Varien_Event_Observer $observer
* #return Mage_Core_Model_App
* #throws Mage_Core_Exception
*/
protected function _callObserverMethod($object, $method, $observer)
{
if (method_exists($object, $method)) {
$object->$method($observer);
} elseif (Mage::getIsDeveloperMode()) {
Mage::throwException('Method "'.$method.'" is not defined in "'.get_class($object).'"');
}
return $this;
}
$object->$method($observer) will call the observer method on an object, just like before you can set a breakpoint, log to a file or even echo to see what's going on under the hood.
First find the event you are interested in, then try to add bind the event to the observer then, if not working, you can use the second method to debug.
And, yay.... Magento is never simple.
I have an odd one.. I add an audio file, which is an existing file in the request
$file = $request->file('file')[0];
$request->files->add(['audio' => $file]);
When I do dd($request->files->all()) I see newly added 'audio' element. However when I do dd($request->allFiles()) I see original array.
I have even added a replace method for files to the Illuminate\Http\Request to replace $files with no luck.
public function replaceFiles($files) {
$this->files = $files;
}
Am I missing something?
It is as if $request->files and $this->files within $request are two different things.
Just noticed that the problem is with $this->convertedFiles within Illuminate\Http\Request which can be resolved by changing allFiles() to something similar to
/**
* Get an array of all of the files on the request.
*
* #return array
*/
public function allFiles()
{
$files = $this->files->all();
return $this->convertedFiles && count($this->convertedFiles) == count($this->files->all())
? $this->convertedFiles
: $this->convertedFiles = $this->convertUploadedFiles($files);
}
I've decided to extend App\Http\Requests\Request with adjusted allFiles() that I have mentioned above
You can use merge function to add new data into the request object.
$request->merge(['index_name' => $variable]);
I'm having a heck of a time figuring out the code/parameters to hole-punch the Full Page Cache in magento for the Mage_Catalog_Block_Product_Price block. I can get the price to show the first time the page is loaded, but when the cache id is unique, it's not rendering the price properly (it does cache it correctly when it's supposed to be cached) . I know I need to send it parameters, such as product_id etc, but not clear about what (eg 'xx') needs to be sent from getCacheKeyInfo into the cache container for use in $this->_placeholder->getAttribute('xx'). And what needs to be prepared and sent from _renderView() to the price layout/view.
So far I have done the following successfully (they each output testing data)
Created the cache.xml in my module /etc folder
Created the cache container model and verified works (just need settings)
Rewrote/extended the Mage_Catalog_Block_Product_Price into my own model to add the getCacheKeyInfo()
So the problem is that I have tried many variations within the container model's _getCacheId() and _renderBlock() in combination with the getCacheKeyInfo(), like described above. But I am hitting a stumbling block. If anyone can lead me in the right direction, it would be greatly appreciated.
I've been struggling with the Full Page Caching as well.
These are my findings and have been very helpful to me.
Please take a look at: app/code/core/Enterprise/PageCache/Model/Processor/Default.php Line 47
/**
* Check if request can be cached
*
* #param Zend_Controller_Request_Http $request
* #return bool
*/
public function allowCache(Zend_Controller_Request_Http $request)
{
foreach ($this->_noCacheGetParams as $param) {
if (!is_null($request->getParam($param, null))) {
return false;
}
}
if (Mage::getSingleton('core/session')->getNoCacheFlag()) {
return false;
}
return true;
}
Looking at this function there seem to be two ways of avoiding (disabling) the Full Page Cache:
GET Parameter:
You can use the parameters 'store' or 'from_store' prefixed with three underscores to avoid the cache.
Example:
http://magentourl.com/catelog/category/view/id/123?___store
Mage::getUrl('catalog/category/view', array('id' => 123, 'query' => array('___store' => '')))
Session variable:
You could also avoid the Full Page caching by setting a (temporary) session variable:
Mage::getSingleton('core/session')->setNoCacheFlag(true)