Laravel route model binding and fallback - laravel

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?

Related

Laravel not redirects page after sending mail

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.

Making a HTTP Request with id parameter

I have 2 projects running in two diffrent ports
In another project I have written this route
Project A
Route::get("/getBook/{id}", function ($id) {
return response()->json(BlogArticle::find($id));
});
This route will be used as an api for other projects to get the needded books.
In the other project i want to retrive the book by sending a id as a parameter {id} in the url
My approach
Route::get("/api/testing", function () {
$response = Http::get('http://127.0.0.1:900/api/getBook', [
'id' => 1
]);
return $response;
});
But nothing is being returned I am getting 404 not found error?
What am I missing?
Since the route definition is Route::get('/getBook/{id}') it means any GET request to that URL will be handled. The {id} part is a placeholder in the URL, it does not denote a query string part. Therefore you’ll have to include the ID in the URL itself:
$response = Http::get('http://127.0.0.1:900/api/getBook/1')

Method Illuminate\View\View::header does not exist

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');

How to stop GET on a POST route (laravel)

I'm new to laraval. I got this POST route but if someone try the address on the browser it become a GET route and laravel throw a error. Is there a way to throw a 404 page for a GET request on POST route.
Route::post('/step2Validate', 'StepController#step2Validate');
If this route is access as GET "The GET method is not supported for this route. Supported methods: POST."
error is given.
Try this:
Route::get('/step2Validate', function() {
abort(404);
}
);

laravel api with vue 2 js not returning data - could 'localhost:8000' (or '127.0.0.1:8000') be the issue?

I am using the repo https://github.com/mschwarzmueller/laravel-ng2-vue/tree/03-vue-frontend so I have 100% confidence in the reliability of the code. I can post through the laravel api endpoint through the very simple Vue client, and also through Postman. Through Postman I can retrieve the table data array, but not so in the client app. In POSTMAN:
localhost:8000/api/quotes
works just fine.
IN THE vue 2 js CLIENT APP:
methods: {
onGetQuotes() {
axios.get('http://localhost:8000/api/quotes')
.then(
response => {
this.quotes = (response.data.quotes);
}
)
.catch(
error => console.log(error)
);
}
returns nothing. returning the response to Console.log returns nothing. The Network/XHR tab shows the table data rows, but I am not sure what that means.
I know for sure that this code works for others with their unique api endpoints, which I assume may not use localhost or '127:0.0.1:1080.
Edit: in response to request for more info
public function getQuotes()
{
$quotes = Quote::all();
$response = [$quotes];
return response()->json($response, 200);
}
and the relevant route:
Route::get('/quotes', [
'uses' => 'QuoteController#getQuotes'
]);
Just to confirm: I am using verified github repo code in which the ONLY change is my api endpoint addressas mentioned in the first line of the body of this question. . Note that the Laravel back end is also derived from a related repo in Max's fine tutorial. The running code can be seen at
So I really don't think this is a coding error- but is it a configuration error due to me using local host??
EDIT: It WAS a coding error in the laravel controller as shown below
The reason your code isn't working if because you haven't provided a key for your $quotes in your controller but you're looking for it in your vue file (response.data.quotes).
[$quotes] is essentially [0 => $quotes] so when the json response comes through it be 0: [...] not quotes: [...].
To get this to work you just need to change:
$response = [$quotes];
to:
$response = ['quotes' => $quotes];
Furthermore, just an FYI, you don't need to provide the 200 in response->json() as it's the default and you can just return an array and Laravel automatically return the correct json response e.g.:
public function getQuotes()
{
$quotes = \App\Models\Artist::all();
return compact('quotes'); //<-- This is just another way of writting ['quotes' => $quotes]
}
Obviously, you don't have to if you don't want to.
Hope this helps!

Resources