POST request from Postman to Laravel - php

I am trying to send a post request to a Laravel project using Postman, but I get a "419 unknown status" response
routes\web.php:
Route::post('/myaction', 'MymodelController#myaction');
app\Http\Controllers\MymodelController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Mymodel;
class MymodelController extends Controller
{
function myaction()
{
return redirect('/');
}
}
Why does this happen?
The same error appears independently of the content of myaction()

As you are requesting api you should write your route in api.php instead web.php
web.php require _token the csrf field

By default, Laravel use the middleware VerifyCsrfToken.
See this
for more details.
You need to add your URL to the $excludes field inside VerifyCsrfToken class.

Do you have defined route for redirect('/'); in web.php ?

Related

Why auth('api')->user() return me null if I use in api.php but if I use it in web.php it is working

I am using Laravel 7, having this code in api.php
Route::middleware(['auth:api'])->get('/booking','APIController#testauth');
public function testauth() {
$userInfo=auth('api')->user();
}
If I use that, it redirect me to homepage, and if I don't use middleware, it returns me null.
Nevertheless if I use it on web.php it returns me the user.
Where is this difference coming from?
For API please use Auth Facade to get user
Auth::user()

Laravel API Not Found

I'm trying to test my api and for this matter I don't need authentication for my api all I want to do is to share my published posts with api but I get 404 page.
Code
controller
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Post;
class PostController extends Controller
{
public function index(){
return Post::orderby('id', 'desc')->where('status', '=', '1')->get();
}
public function single($slug){
return Post::where('slug', $slug)->where('status', '=', '1')->firstOrFail();
}
}
api.php (routes folder)
Route::get('posts', 'API\PostController#index');
Route::get('posts/{slug}', 'API\PostController#single');
I tried to access my api posts with url like: http://newapp.test/api/posts and it returns 404 error.
Any idea?
Update
api.php
<?php
use Illuminate\Http\Request;
// Route::middleware('auth:api')->get('/user', function (Request $request) {
// return $request->user();
// });
Route::get('posts', 'API\PostController#index');
Route::get('posts/{slug}', 'API\PostController#single');
Leave all things as it is and RUN Command
php artisan route:clear
Run command php artisan route:list. It will show you list of available routes in your application. In this way, you could first verify the existing routes and the ones you are trying to access.
My API mistake was: redirecting back
if($validator->fails()){ return redirect()->back()->withInput()->with('error',$validator->errors()->first());}
corrected by: returning a JSON
if($validator->fails()){ return $this->responseWithError($validator->errors()->first()); }
responseWithError is a helper method that returns JSON in a certain structure

Laravel API controller returns 404 when hit through Twilio

I am trying to set up a route that I can let Twilio hit, that will return a response from Laravel.
But every Twilio request kicks back a 404 Http Response.
Feels like I've got something misconfigured.
I have
Created ControllerClass SmSController with a reply method.
Added my route to routes/api.php to hit the controller.
Added my URL to the $except property in app/Http/Middleware/VerifyCsrfToken.php
Here's my app/Http/Controllers/SmsController.php:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Twilio\Twiml;
class SmsController extends Controller
{
public function reply(Request $request) {
$response = new Twiml;
$response->message("Hello World!");
print $response;
}
}
And Here's my routes/api.php:
Route::group([
'middleware' => 'auth:api'
], function () {
//
});
Route::post('sms/reply', 'SmsController#reply');
And inside the class VerifyCsrfToken I have:
protected $except = [
'sms/reply'
];
Edit: I should mention, I have Twilio to hit the URL: https://www.MYWEBSITE.com/sms/reply, which I think should correspond to the route I set up in api.pip
All the routes inside of api.php are prefixed with api inside a url, so your sms/reply is actually api/sms/reply, does this make sense?

Laravel 5 Basic Auth custom error

In Laravel 5, if basic auth fails for a user then the default message that is returned is an "Invalid Credentials" error string. I am trying to return a custom JSON error when this situation occurs.
I can edit the returned response in vendor/laravel/framework/src/Illuminate/Auth/SessionGuard.php
however I have not seen where you can change the behavior of this message outside of the vendor directory. Is there a way?
Looks like there were some ways to do this through Laravel 4: Laravel 4 Basic Auth custom error
Figured it out, looks like I had to create custom middleware to handle this.
Note that this solution didn't work when calling my API from my browser, only when calling it from a tool like Postman. For some reason when calling it from my browser I always got the error before seeing the basic auth prompt.
In my controller I changed the middleware to my newly created one:
$this->middleware('custom');
In Kernel I added the location for it:
protected $routeMiddleware = [
'auth.basic.once' => \App\Http\Middleware\Custom::class,
]
Then I created the middleware. I used Stateless Basic Auth since I'm creating an API:
<?php
namespace App\Http\Middleware;
use Auth;
use Closure;
use Illuminate\Http\Request as HttpRequest;
use App\Entities\CustomErrorResponse
class Custom
{
public function __construct(CustomErrorResponse $customErrorResponse) {
$this->customErrorResponse = $customErrorResponse
}
public function handle($request, Closure $next)
{
$response = Auth::onceBasic();
if (!$response) {
return $next($request);
}
return $this->customErrorResponse->send();
}
}

How to access session created in a blade.php file of Laravel 5.2 in a Controller Method?

I just moved a project from laravel 4.0 to laravel 5.2. Am using a fresh installation of laravel 5.2 as suggested by Taylor. i have successfully transfer all files and web app works fine.
My challenge is that i have a page called page.blade.php that stores some value in session {{ Session::put('item', $itemSelected) }} base on the user choice and i have a Session::get('item') in my controller to receive this and process some logic.
The session returns null in the controller but when i add {{Session::get('item')}} in to page.blade.php it display value stored in $itemSelected. I also observe that session created in controller method can be access by the page.blade.php but the session created by the page.blade.php can't be access by the controller method.
Am a little bit confuse here, i need help. This process worked fine in laravel 4.0 before i moved to laravel 5.2
Here is my route
route::group(['middleware' => ['web']], function () {
Route::get('page', 'Website\PageController#mypage');
});
Page.blade.php
'''''
$itemSelected= 'Page 1';
{{Session::put('item' , $itemSelected)}}
Page 1
......
My Controller
<?php
namespace App\Http\Controllers\Website;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\Authuser;
use View;
use Redirect;
use Session;
return
class PageController extends Controller {
public function mypage()
{
...
$selectedPage = Session::get('item'); //this suppose to return "Page 1" but returns null
....
}
}
I can't call this an answer to this issue but another way to get the job done.
From the view page.blade.php, I pass the value $itemSelected as a $_GET variable on a url. When link is clicked the controller picks the value from the request with Input::get('item'). Then persist the return value from request into Session (Session::put('item',$itemSelected). This got the task done.
Because it hasn't been set yet, you set it in the view, which is created after you run that line. I am guessing that is what the '...' implies.

Categories