I'm trying to produce a js file to let other webmasters use my news headlines in their websites:
Route::get('/script/news/{slug}/{count}.js',function($slug,$count) {
return view('webmaster_script')->
with(compact("slug","count"))->
header('Content-Type', 'application/javascript');
});
But it says
BadMethodCallException Method Illuminate\View\View::header does not
exist
How can I fix it?
Script content is generated successfully . I just want to change the MIME type.
Thanks in advance
Laravel's documentation gives following example
If you need control over the response's status and headers but also need to return a view as the response's content, you should use the view method:
return response()
->view('hello', $data, 200)
->header('Content-Type', $type);
So following should work:
return response()
->view('webmaster_script', compact("slug", "count"))
->header('Content-Type', 'application/javascript');
Related
I am sending a mail and after mail is send I want to redirect user to a specific url
$mail = Mail::send('test.mail', ['a' => 'a'], function (Message $message) {
$message->to(['hod#vu.edu.pk', 'student#vu.edu.pk',]);
$message->from('stms#vu.edu.pk');
$message->subject('Test Mail');
});
// dd($mail);
return response()->redirectToRoute('allocate_supervisor')
->with('message', 'Supervisor Assigned and sent to HoD for approval.');
I have tried to return redirect()->route(), url(), and redirect('allocate_supervisor') but each time same issue.
dd($mail); works fine and shows output but on redirect it shows blank page.
Also request status code is 200.
Also tried
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
before return still no output
There are several ways to generate a RedirectResponse instance. The simplest method is to use the global redirect helper:
return redirect('/allocate_supervisor');
make sure 'allocate_supervisor' route must be present in your web.php file.
if you have named routes, you may use route() method.
return redirect()->route('/allocate_supervisor');
I was calling storePhase function from store function and returning response from storePhase function which was being overridden in store function and I was receiving blank page...
I moved this response code to store function and it worked fine.
I am working on an api with laravel. For this, I wanna return a json response for all 404 errors. I created this fallback route and placed it at the end of the api.php:
Route::fallback(function(){
return response()->json(['message' => 'Not Found.'], 404);
})->name('api.fallback.404');
When I now enter an invalid url like /xyz I get the json response as expected.
But when I use route model binding:
Route::get('/projects/{project}', function (\App\Models\Project $project) {
return $project->toArray();
});
and try to get a non existing project (for example /projects/9999), then I get the standard laravel 404 HTML response and not my json one.
How to fix this?
$files = $request->file('images'); // return {}
$_FILES['images']; // return {"name":"sample-passport.jpg","type":"image\/jpeg","tmp_name":"D:\\xampp\\tmp\\php4AD9.tmp","error":0,"size":264295}
Have you tried to remove the Content-Type header? According to this Github issue, it seems to be a problem.
So, I set up a new Laravel installation to test this out and it's working fine on my side. Of course, there's no authorisation whatsoever but this shouldn't impact the result too much.
routes/api.php
Route::post('/profile/upload_image', function (Request $request) {
dd($request->file('image'));
});
Postman configs
Your post input attribute type change file after upload you will get a response.enter image description here
I use zend framework 2 and try to return an created with gd2 library jpeg image . but it doesn't work. could you look my code what's the problem? My code is run with plain php in normally but in zf2 problem?
class PictureController extends AbstractActionController
{
public function colorPaletteAction(){
....
....
//canvas created at above.
imagejpeg($canvas);
imagedestroy($canvas);
$response = $this->getResponse();
return $response->getHeaders()->addHeaderLine('Content-Type', 'image/jpeg');
}
}
imagejpeg outputs the data immediately which you don't want to do. You can either use the output buffer to capture this data or write it to a file first. The output buffer is probably easiest:
public function colorPaletteAction()
{
// [create $canvas]
ob_start();
imagejpeg($canvas);
$imageData = ob_get_contents();
ob_end_clean();
imagedestroy($canvas);
$response = $this->getResponse();
$response->getHeaders()->addHeaderLine('Content-Type', 'image/jpeg');
$response->setContent($imageData);
return $response;
}
If this doesn't work, temporarily comment out the Content-Type header line to see what output you're getting. Make sure there aren't any errors or HTML in the output.
You set the Content-Type header to 'image/png' instead of 'image/jpeg'.
Also try adding the content-transfer-encoding and content-length headers:
$response->getHeaders()->addHeaderLine('Content-Transfer-Encoding', 'binary')
->addHeaderLine('Content-Length', mb_strlen($yourJpegContent));
I also don't see you adding the actual content to the response:
$response->setContent($yourJpegContent);
where $yourJpegContent contains the binary image data.
I trying to pass some json to a controller in cakePHP 2.5 and returning it again just to make sure it is all going through fine.
However I getting no response content back. Just a 200 success. From reading the docs I am under the impression that if I pass some json then the responseHandler will the return json as the response.
Not sure what I am missing.
Data being passed
var neworderSer = $(this).sortable("serialize");
which gives
item[]=4&item[]=3&item[]=6&item[]=5&item[]=7
appController.php
public $components = array(
'DebugKit.Toolbar',
'Search.Prg',
'Session',
'Auth',
'Session',
'RequestHandler'
);
index.ctp
$.ajax({
url: "/btstadmin/pages/reorder",
type: "post",
dataType:"json",
data: neworderSer,
success: function(feedback) {
notify('Reordered pages');
},
error: function(e) {
notify('Reordered pages failed', {
status: 'error'
});
}
});
PagesController.php
public function reorder() {
$this->request->onlyAllow('ajax');
$data = $this->request->data;
$this->autoRender = false;
$this->set('_serialize', 'data');
}
UPDATE:
I have now added the following to the routes.php
Router::parseExtensions('json', 'xml');
and I have updated my controller to
$data = $this->request->data;
$this->set("status", "OK");
$this->set("message", "You are good");
$this->set("content", $data);
$this->set("_serialize", array("status", "message", "content"));
All now works perfectly.
A proper Accept header or an extension should to be supplied
In order for the request handler to be able to pick the correct view, you need to either send the appropriate Accept header (application/json), or supply an extension, in your case .json. And in order for extensions to be recognized at all, extension parsing needs to be enabled.
See http://book.cakephp.org/...views.html#enabling-data-views-in-your-application
The view only serializes view vars
The JSON view only auto-serializes view variables, and from the code you are showing it doesn't look like you'd ever set a view variable named data.
See http://book.cakephp.org/...views.html#using-data-views-with-the-serialize-key
The view needs to be rendered
You shouldn't disable auto rendering unless you have a good reason, and in your case also finally invoke Controller:render() manually. Currently your action will not even try to render anything at all.
CakeRequest::onlyAllow() is for HTTP methods
CakeRequest::onlyAllow() (which btw is deprecated as of CakePHP 2.5) is for specifying the allowed HTTP methods, ie GET, POST, PUT, etc. While using any of the available detectors like for example ajax will work, you probably shouldn't rely on it.
Long story short
Your reorder() method should look more like this:
public function reorder() {
if(!$this->request->is('ajax')) {
throw new BadRequestException();
}
$this->set('data', $this->request->data);
$this->set('_serialize', 'data');
}
And finally, in case you don't want/can't use the Accept header, you need to append the .json extension to the URL of the AJAX request:
url: "/btstadmin/pages/reorder.json"
and consequently enable extension parsing in your routes.php like:
Router::parseExtensions('json');
ps
See Cakephp REST API remove the necessity of .format for ways to use the JSON view without using extensions.
Output your json data
public function reorder() {
$this->request->onlyAllow('ajax');
$data = $this->request->data;
$this->autoRender = false;
$this->set('_serialize', 'data');
echo json_encode($data);
}