Anne  de Morel

Anne de Morel

1656277200

Comment Vérifier L'en-tête Personnalisé Dans L'api De Repos Laravel 5

Dans le projet Laravel 5 REST API, nous devons parfois créer notre propre en-tête personnalisé pour la sécurité. comme : 'X-hardik':'123456'. c'était un exemple, cela signifie que dans votre projet actuel, chacune de vos demandes passe par votre propre en-tête personnalisé, comme je vous le donne par exemple. Cet en-tête personnalisé peut améliorer votre sécurité. nous pouvons également vérifier que votre en-tête est bon ou mauvais.exemple :

Votre requête Jquery ou AngularJS

    $.ajax({  
         type: 'POST',  
         dataType: 'json',  
         url: 'http://test.hd/api/login',  
         headers: { 'X-hardik': '123456'},  
         data: {'email':'savanihd@gmail.com','password':'123456'}  
    }).done(function(data){  
        alert('Login Successfully');  
    }).fail(function(jqXHR, ajaxOptions, thrownError){  
         alert(jqXHR.responseText);  
    });  

Il s'agit de votre requête Jquery normale avec l'en-tête personnalisé "X-hardik" et le mot de passe "123456".

Maintenant, comment vérifier cette demande dans votre projet laravel.

lancez d'abord cette commande et créez un middleware.

php artisan make:middleware checkHeader

Ok, vous pouvez maintenant vérifier le chemin de votre projet : fichier app/Http/Middleware/checkHeader.php

ajouter du contenu sur ce fichier.

namespace App\Http\Middleware;  
  
use Closure;  
use Illuminate\Contracts\Auth\Guard;  
use Response;  
  
class checkHeader  
{  
    /** 
     * The Guard implementation. 
     * 
     * @var Guard 
     */  
  
    /** 
     * Handle an incoming request. 
     * 
     * @param  \Illuminate\Http\Request  $request 
     * @param  \Closure  $next 
     * @return mixed 
     */  
    public function handle($request, Closure $next)  
    {  
        if(!isset($_SERVER['HTTP_X_HARDIK'])){  
            return Response::json(array('error'=-->'Please set custom header'));  
        }  
  
        if($_SERVER['HTTP_X_HARDIK'] != '123456'){  
            return Response::json(array('error'=>'wrong custom header'));  
        }  
  
        return $next($request);  
    }  
}

Vous devez maintenant ajouter le fichier app/Http/Kernel.php pour attribuer le nom du middleware.

namespace App\Http;  
  
use Illuminate\Foundation\Http\Kernel as HttpKernel;  
  
class Kernel extends HttpKernel  
{  
    /** 
     * The application's global HTTP middleware stack. 
     * 
     * @var array 
     */  
    protected $middleware = [  
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,  
        \App\Http\Middleware\EncryptCookies::class,  
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,  
        \Illuminate\Session\Middleware\StartSession::class,  
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,  
        \App\Http\Middleware\VerifyCsrfToken::class,  
    ];  
  
    /** 
     * The application's route middleware. 
     * 
     * @var array 
     */  
    protected $routeMiddleware = [  
        'auth' =--> \App\Http\Middleware\Authenticate::class,  
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,  
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,  
        'checkHeader' => \App\Http\Middleware\checkHeader::class,  
    ];  
}  

Ok maintenant vous pouvez utiliser dans votre itinéraire comme ceci :

Route::post('api/login', array('uses' => 'APIAuthController@login','middleware' => ['checkHeader']));

Essaye ça... 

Source : https://www.itsolutionstuff.com/post/how-to-create-and-check-custom-header-with-middleware-for-rest-api-in-laravel-5-example.html

#middleware #restapi #laravel 

What is GEEK

Buddha Community

Comment Vérifier L'en-tête Personnalisé Dans L'api De Repos Laravel 5
Anne  de Morel

Anne de Morel

1656277200

Comment Vérifier L'en-tête Personnalisé Dans L'api De Repos Laravel 5

Dans le projet Laravel 5 REST API, nous devons parfois créer notre propre en-tête personnalisé pour la sécurité. comme : 'X-hardik':'123456'. c'était un exemple, cela signifie que dans votre projet actuel, chacune de vos demandes passe par votre propre en-tête personnalisé, comme je vous le donne par exemple. Cet en-tête personnalisé peut améliorer votre sécurité. nous pouvons également vérifier que votre en-tête est bon ou mauvais.exemple :

Votre requête Jquery ou AngularJS

    $.ajax({  
         type: 'POST',  
         dataType: 'json',  
         url: 'http://test.hd/api/login',  
         headers: { 'X-hardik': '123456'},  
         data: {'email':'savanihd@gmail.com','password':'123456'}  
    }).done(function(data){  
        alert('Login Successfully');  
    }).fail(function(jqXHR, ajaxOptions, thrownError){  
         alert(jqXHR.responseText);  
    });  

Il s'agit de votre requête Jquery normale avec l'en-tête personnalisé "X-hardik" et le mot de passe "123456".

Maintenant, comment vérifier cette demande dans votre projet laravel.

lancez d'abord cette commande et créez un middleware.

php artisan make:middleware checkHeader

Ok, vous pouvez maintenant vérifier le chemin de votre projet : fichier app/Http/Middleware/checkHeader.php

ajouter du contenu sur ce fichier.

namespace App\Http\Middleware;  
  
use Closure;  
use Illuminate\Contracts\Auth\Guard;  
use Response;  
  
class checkHeader  
{  
    /** 
     * The Guard implementation. 
     * 
     * @var Guard 
     */  
  
    /** 
     * Handle an incoming request. 
     * 
     * @param  \Illuminate\Http\Request  $request 
     * @param  \Closure  $next 
     * @return mixed 
     */  
    public function handle($request, Closure $next)  
    {  
        if(!isset($_SERVER['HTTP_X_HARDIK'])){  
            return Response::json(array('error'=-->'Please set custom header'));  
        }  
  
        if($_SERVER['HTTP_X_HARDIK'] != '123456'){  
            return Response::json(array('error'=>'wrong custom header'));  
        }  
  
        return $next($request);  
    }  
}

Vous devez maintenant ajouter le fichier app/Http/Kernel.php pour attribuer le nom du middleware.

namespace App\Http;  
  
use Illuminate\Foundation\Http\Kernel as HttpKernel;  
  
class Kernel extends HttpKernel  
{  
    /** 
     * The application's global HTTP middleware stack. 
     * 
     * @var array 
     */  
    protected $middleware = [  
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,  
        \App\Http\Middleware\EncryptCookies::class,  
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,  
        \Illuminate\Session\Middleware\StartSession::class,  
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,  
        \App\Http\Middleware\VerifyCsrfToken::class,  
    ];  
  
    /** 
     * The application's route middleware. 
     * 
     * @var array 
     */  
    protected $routeMiddleware = [  
        'auth' =--> \App\Http\Middleware\Authenticate::class,  
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,  
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,  
        'checkHeader' => \App\Http\Middleware\checkHeader::class,  
    ];  
}  

Ok maintenant vous pouvez utiliser dans votre itinéraire comme ceci :

Route::post('api/login', array('uses' => 'APIAuthController@login','middleware' => ['checkHeader']));

Essaye ça... 

Source : https://www.itsolutionstuff.com/post/how-to-create-and-check-custom-header-with-middleware-for-rest-api-in-laravel-5-example.html

#middleware #restapi #laravel 

Devan  Johnson

Devan Johnson

1600713120

Laravel 5.5 Artisan Console Tutorial

Laravel 5.5 Artisan Console Tutorial is today’s topic. Artisan Command Line Interface comes with brand new Laravel project out of the box. There are so many commands Laravel application provides us by default. There so many tasks in your application that can be very well handled by command line tools. So this tutorial is dedicated to Laravel 5.5 Commands. You can list all the Laravel 5.5 Commands by the typing following command.

php artisan list

Laravel 5.5 Artisan Console Tutorial

If you are new to Laravel 5.5 then check out my these tutorials on this blog.

  1. Laravel 5.5 Tutorial With Example From Scratch
  2. Laravel 5 Middleware Tutorial With An Example

#laravel #laravel 5.5 #laravel 5.5 artisan

Seamus  Quitzon

Seamus Quitzon

1595201363

Php how to delete multiple rows through checkbox using ajax in laravel

First thing, we will need a table and i am creating products table for this example. So run the following query to create table.

CREATE TABLE `products` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
 `description` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
 `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
 `updated_at` datetime DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

Next, we will need to insert some dummy records in this table that will be deleted.

INSERT INTO `products` (`name`, `description`) VALUES

('Test product 1', 'Product description example1'),

('Test product 2', 'Product description example2'),

('Test product 3', 'Product description example3'),

('Test product 4', 'Product description example4'),

('Test product 5', 'Product description example5');

Now we are redy to create a model corresponding to this products table. Here we will create Product model. So let’s create a model file Product.php file under app directory and put the code below.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = [
        'name','description'
    ];
}

Step 2: Create Route

Now, in this second step we will create some routes to handle the request for this example. So opeen routes/web.php file and copy the routes as given below.

routes/web.php

Route::get('product', 'ProductController@index');
Route::delete('product/{id}', ['as'=>'product.destroy','uses'=>'ProductController@destroy']);
Route::delete('delete-multiple-product', ['as'=>'product.multiple-delete','uses'=>'ProductController@deleteMultiple']);

#laravel #delete multiple rows in laravel using ajax #laravel ajax delete #laravel ajax multiple checkbox delete #laravel delete multiple rows #laravel delete records using ajax #laravel multiple checkbox delete rows #laravel multiple delete

Seamus  Quitzon

Seamus Quitzon

1595212560

5 Laravel’s Hidden Gems

1. Stop on first validation error

By default, Laravel will check for all validation rules and return a list of errors. But if you want to stop this process after first validation failure, that’s how you can achieve it

$request->validate([
    'title' => 'bail|required|unique:posts|max:255',
    'body' => 'required',
]);

2. Find many

Most of us developers have used Eloquent’s method find to search for one specific id, but do you know we can pass multiple ids to find which will return a collection.

// Will return Eloquent Model
$user = User::find(1);
// Will return Eloquent Collection
$users = User::find([1,2,3]);

3. Relationship but with condition

Some times we need to apply where on relationships, instead of calling relationship and then chaining where we can achieve it by following:

// app/Post.php model
public function comments()
{
    return $this->hasMany(Comment::class);
}
public function approved_comments()
{
    return $this->hasMany(Comment::class)->where('approved', 1);
}

4. Rename pivotal table

In pivot table, if you want to rename pivot to some thing else, this can be done by following code:

public function podcasts() {
return $this->belongsToMany('App\Podcast')
->as('subscription')
->withTimestamps();
}
// Then somewhere in Controller...
$podcasts = $user->podcasts();
foreach ($podcasts as $podcast) {
// instead of $podcast->pivot->created_at ...
echo $podcast->subscription->created_at;
}

#laravel #php #find many laravel #prepare for validation laravel #relationship but with condition laravel #rename pivotal table laravel #stop on first validation error laravel

Juned Ghanchi

1621508419

Laravel App Development Company in India, Hire Laravel Developers

Hire our expert team of Laravel app developers for flexible PHP applications across various cloud service providers.

With this easy build technology, we develop feature-rich apps that make your complex business process a lot easier. Our apps are,

  • More secure and scalable.
  • A good framework lets you manage and organize resources better.
  • And have a rich community base.

Get your business a best in classlaravel app. Hire laravel app developers in India. We have the best organizational set-up to provide you the most advanced app development services.

#laravel app development company india #hire laravel developers india #laravel app development company #hire laravel developers #laravel development agency #laravel app programmers