how to do server side api validation in laravel 5.4 - api

How to send send error message in json format to postman in laravel 5.4
//Controller
public function store(Request $request)
{
$validator = Validator::make($request->all(),[
'department_name' => 'required',
]);
if($validator->fails())
{
return $validator->errors()->all();
}
Department::create($request->all());
return Response::json(['message' => 'Added','status' => 201],201);
}

You can simply return the validation errors as json response like this :
if ($validator->fails()) {
return response()->json(['errors'=>$validator->errors()]);
}

Related

Laravel api returning 401 (Authentication failed) even when logged in

i have created a simple crud app using Laravel 6 and VueJs it was working fine before but when i added middleware auth to api routes group it returns error 401 even when logged in.
here is api.php
Route::group(['middleware' => ['api','auth']], function(){
Route::get('contacts',function(){
return Contact::latest()->orderBy('created_at','desc')->get();
});
Route::get('contact/{id}',function($id){
return Contact::findOrFail($id);
});
Route::post('contact/store',function(Request $request){
return Contact::create([
'name' => $request->name,
'email' => $request->email,
'phone' => $request->phone
]);
});
Route::patch('contact/{id}',function(Request $request, $id){
$contact = Contact::findOrFail($id);
$contact->name = $request->name;
$contact->email = $request->email;
$contact->phone = $request->phone;
$contact->save();
return $contact;
});
Route::delete('contact/{id}',function($id){
return Contact::destroy($id);
});
});

auth:api middleware not working in live server using laravel

auth:api middleware not working in live server using laravel
Route::group(['prefix' => 'business_entry_api','middleware' => 'auth:api'], function () {
// function here
}
you ca go with auth('api')->user(). It'll return the authenticated user even if middleware is not specifically used.
use like below on your api file:
public function __construct()
{
$this->middleware(function ($request,Closure $next) {
$this->user = Auth('api')->user();
return $next($request);
});
}

Method Illuminate\Auth\RequestGuard::attempt does not exist

I am new to both laravel and lumen.
I was creating a login api with oauth2.0 in lumen 5.6, i have installed passport and generated token.
Below is my login controller function and it is working fine. It returns token.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Route;
//use Illuminate\Support\Facades\DB;
use App\User;
use Auth;
public function login(Request $request)
{
global $app;
$proxy = Request::create(
'/oauth/token',
'post',
[
'grant_type' => env('API_GRAND_TYPE'),
'client_id' => env('API_CLIENT_ID'),
'client_secret' => env('API_CLIENT_SECRET'),
'username' => $request->username,
'password' => $request->password,
]
);
return $app->dispatch($proxy);
}
Since i have to check user status apart from username and password, i need to check the user credential first. so i do like this.
public function login(Request $request)
{
$credentials = $request->only('username', 'password');
if (Auth::attempt($credentials)) {
return ['result' => 'ok'];
}
return ['result' => 'not ok'];
}
Here i am getting this error.
Method Illuminate\Auth\RequestGuard::attempt does not exist.
So i tried Auth::check instead of Auth::attempt.
Now there is no error but it always return false even though the credentials are valid.
I searched a lot for a solution but i didn't get.
The function guard is only available for routes with web middleware
public function login() {
if(Auth::guard('web')->attempt(['email' => $email, 'password' => $password], false, false)) {requests
// good
} else {
// invalid credentials, act accordingly
}
}
Changing default guard to "web" fixed my problem.
config/auth.php:
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
using jwt it's worked for me
1-Auth::attempt($credentials)
just replace line 1 to line 2
2-$token = Auth::guard('api')->attempt($credentials)

How to use API call in service in Iconic2

I am calling following function on click of button.
login.ts
public login() {
this.showLoading()
this.http.get('http://laravel.dev/test').map(res => res).subscribe(data => {
console.log(data)
},
error => {
this.showError(error);
});
}
What I want that this API call should be come from service file. As I am new to Ionic 2 That's Why I am unable to get how can I call above API through service and receive it in login.ts.
auth.service.ts
public login(credentials) {
// Here I want to call Above API and return it to the `login.ts`
}
Please help me.
The http.get request is an Observable. You can return the observable from the service and subscribe in the component/page.
auth.service.ts
public login(credentials) {
return this.http.get('http://laravel.dev/test').map(res => res.json())
}
map function returns the data after decoding the json response assuming your http returns json.
login.ts
public login() {
this.showLoading()
this.authService.login(credentials).subscribe(data => {
console.log(data)
},
error => {
this.showError(error);
},
()=>this.dismissLoading());
}
Inject the service through the constructor in your component and subscribe to the login function.

Basic authentication in Lumen

I have already written an API call for check authentication using Laravel. I need to move that controller to Lumen for use it as micro service.
This is my controller in Laravel.
public function byCredantial(Request $request)
{
$user = [
'email' => $request->input('email'),
'password' => $request->input('password')
];
if (Auth::attempt($user)) {
$response = $this->getSuccess(Auth::user()->id);
return response()->json($response, 200);
} else {
$response = $this->getError($user);
return response()->json($response, 401);
}
}
Lumen doc is not provide how to do such authentication. They has not function for check creadential is correct. How can i do this in Lumen. Is this possible?
You can do this in Lumen. Facades are disabled by default (if you want to enable it you can see the instructions in the documentation), but I would not recommend enabling the facades as the add additional overhead to your application. Instead, I would modify your function to call app('auth'). This will return the class that the Auth facade proxies without loading all the other facades.
public function byCredantial(Request $request)
{
$user = [
'email' => $request->input('email'),
'password' => $request->input('password')
];
$auth = app('auth');
if ($auth->attempt($user)) {
$response = $this->getSuccess($auth->user()->id);
return response()->json($response, 200);
} else {
$response = $this->getError($user);
return response()->json($response, 401);
}
}
Also, I would recommend reading the authentication documentation and placing the bulk of this code in the AuthServiceProvider.