API endpoint in Laravel hook - laravel

Is it possible to establish an API endpoint in a laravel voyager hook?
All the documentation I can find shows how to set up a listener for a web request, but these endpoints will not take a post.

Just create the post route in your api routes file.
Example:
// routes/api.php
<?php
Route::post('/webhooks', 'WebhooksController');
// app/Http/Controllers/Api/WebhooksController
public function __invoke(Request $request)
{
// handle webhook
}
Then posting data to yourapp.test/api/webhooks should work.

Related

Route type delete does not work in Laravel

I have following route and works
Route::post("delete-role", [RoleApiController::class, "Remove"]);
I tested it through postman like this
http://localhost/delete-role?api_token=hcvhjbhjb12khjbjhc876
Now, if I change above route and convert to type delete..
Route::delete("delete-role/{role_id}", [RoleApiController::class, "Remove"]);
it does not work. I get below error. It seems to be the reason that the api_token is missing.
I get same error when trying to update route like below
Route::delete("delete-role/{role_id}/{api_token}", [RoleApiController::class, "Remove"]);
You have to set header of your request as:
"Accept": "application/json"
in postman.
If you don't set the required header for api, Laravel Passport can't understand request as an API client and so it will redirect to a /login page for the web.
Or you can set a middleware to check it in code:
public function handle($request, Closure $next)
{
if(!in_array($request->headers->get('accept'), ['application/json', 'Application/Json']))
return response()->json(['message' => 'Unauthenticated.'], 401);
return $next($request);
}
You have an incomplete details. but I see few issues here.
You seem to be using web routes for your API requests which is a bad set-up
You do not have a route with login name.
based on the error you posted, your request seems to successfully destroyed the token and logged you out, then called the middleware App\Http\Middleware\Authenticate which supposed to redirect your request to login route which does not exist and the reason you are getting that error.
You can see from that Authenticate middleware it will supposed to redirect you to login route for unauthenticated request. thats why you need to use the api routes so you can handle the response manually
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* #param \Illuminate\Http\Request $request
* #return string|null
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
}
Also, I'm not so sure about this, but the reason you are not getting the same issue with your POST request is probably because your POST request does not call the Authenticate middleware or whatever in your routes file or class function that calls the authenticate middleware.
But again, just use api routes if you don't want un-authenticated request to automatically redirect your request to login routes which does not exist in your application
The problem is that he doesn't define route ('login'),
add in Exceptions/Handler.php
$this->renderable(function (AuthenticationException $e, $request) {
if ($request->is('api/*')) {
return response()->json(['meassge' => 'Unauthenticated']);
}
});
Then you should use Passport Or Sanctum for auth with Api,
Continue from here https://laravel.com/docs/9.x/passport
Probably, this thread could help you. Route [login] not defined
(OR)
You need to setup auth scaffolding to get login route defined.
Important: your project will be overridden if you setup auth scaffold.
So, I would only recommend doing this if it is a new project or a testing app.
See this for detail doc but install Laravel Breeze would be suffice.
It Appears you have called route('login') without having defined it in your routes, Please remove route('login') from your code or define it in your routes. eg::
Route::get('login', [YourController::class, 'methodName'])->name('login');

how to prepare api using laravel and vue.js

good day;
I am new in vue.js and I want to build API in my project using vue.js and laravel
I have some question and answer because I got confused
I have services controller that return all service
as below:-
class ServicesController extends Controller
{
public function Services()
{
//get all serveice
$services=Services::where(['deleted'=>1,'status'=>1])->get();
return response()->json($services);
}
}
and API route as below:-
Route::get('/Servicess', 'API\ServicesController#Services');
it is necessary to make a component to send a request to using
Axios request to get data and if yes how to tell the mobile developer about a link to access it.
i want the steps from vue.js side to
prepare data and send it using Axios
You can not use your front-end javascript code inside php controllers, there are two ways to use the data; First: send it via the request. Second: fetch the required data at the back-end side and use it there.
Also there are many alternatives to Axios like the fetch api etc.
Update#1:
example controller
use Illuminate\Http\Request;
class ExampleController extends Controller
{
public function exampleMethod(Request $request){
$name = $request->input('name');
//DO sth
}
}
Route in api.php:
Route::get('/users', 'API\ExampleController#exampleMethod');

laravel broadcast channel is not calling after changing auth endpoint

i am developing teacher and student chat system in laravel and vuejs using pusher. So as i read from documentation that laravel by default do the user authentication for private and presence channel so both my model are different one is student and other one is teacher both are not extend from Authenticatable so what i did is change the authendpoint and make a new route and return the pusher ath:key i,m successfully doing that but now the problem is after returning auth response Echo.private is not calling my channel
This is my Channel.php file code
Broadcast::channel('student-messages.{id}', function($id) {
return true;
},['guards'=>['web']]);
This is my chat app file code
window.Echo.private(`student-messages.${this.student.id}`)
.listen('NewMessage',(e)=>{
console.log(e);
});
This is my route in web.php
Route::post('/custom/endpoint/auth',function (Request $request){
$pusher = new Pusher\Pusher(env('PUSHER_APP_KEY'),env('PUSHER_APP_SECRET'), env('PUSHER_APP_ID'));
return $pusher->socket_auth($request->request->get('channel_name'),$request->request->get('socket_id'));
});

Use Policies with apiResource Routes

Currently I'm writing a Laravel 5.6 REST api. Now I want to secure my endpoints:
Each user in my application has a role. Based on that the user should be able to access some endpoints and otherwise should get a 403 error. For this I would like to use Policies because, when used as middleware, they can authorize actions before the incoming request even reaches my route or controller.
I declare my endpoints like this:
Route::apiResource('me', 'UserController');
My problem now is that if I want to use Policies as middleware I have to specify the (HTTP) method like this middleware('can:update,post'). How should I do this when I use apiResource in my route declaration?
BTW: Currently I have written a FormRequest for each method (which is a pain) and do the authorization there. Can I simply return true in the authorize method after switching to Policies middleware?
Since you are using FormRequest::class to validate the request data, it is best practice to first check is the user is authorized to make the request. For Laravel 5.6 the cleanest solution would be to specify each policy manually in the __construct() method of your resource controller.
public function __construct()
{
$this->middleware('can:viewAny,App\Post')->only('index');
$this->middleware('can:create,App\Post')->only('store');
$this->middleware('can:view,post')->only('show');
$this->middleware('can:update,post')->only('update');
$this->middleware('can:delete,post')->only('delete');
}
If your were validating form data inside your controller instead of using FormRequest::class, a cleaner solution would be to also authorize the user inside the controller.
public function store(Request $request)
{
$this->authorize('create', Post::class);
// The user is authorized to make this request...
$request->validate([
//Validation Rules
});
// The form data has been successfully validated...
// Controller logic...
}
Since Laravel 5.7 you can do all of this using one line of code on your controller's __construct() method.
public function __construct()
{
$this->authorizeResource(Post::class, 'post');
}
You can define route groups, routes that have a common behaviour (middleware, prefix etc. ).
The following should work:
Route::middleware('can:update,post')->group(function () {
Route::apiResource('me', 'UserController');
//more routes
});
You can prefix routes as well:
Route::middleware('can:update,post')->group(function () {
Route::prefix('users')->group(function () {
Route::apiResource('me', 'UserController'); //Translated to ex: /users/me
Route::prefix('books')->group(function () {
Route::apiResource('{book}', 'UserController'); //Translated to ex: /users/me/book_1
});
});
});
P.S: I haven't used resources before but it should do the job

Handle every request in laravel 5

I have laravel project and I want to create access log table. in route file is it possible handle every request and its parameters to store in database.
You can create middleware and handle all request with it. Then put all your routes in a group to apply your middleware.
Route::group(['middleware' => 'yourMiddleware'], function () {
// All your routes
});
Yes, it is possible. Create your own service provider and register it, then in boot method create script that logs requests to database.
Example:
public function boot()
{
if (! app()->runningInConsole()) {
App\Request::create(['payload'=>serialize(app('request')->all())]);
}
}

Resources