Connect with us

Laravel 7 comes with Easy Implicit Route Model Binding

kizinho

Published

on

Follow
Laravel 7 comes with Easy Implicit Route Model Binding
Photo: Naijacrawl

Laravel 7 will be out 2020 with new awesome features. You can clean the way routing is been done with one line of code.

But you can try the dev version by running this code

laravel new example --dev


In laravel 7 you can bind routes like this:


Route::get('/posts/{post:slug}', function (Post $post) {
    // ...
});


Currently, Laravel 6 and below requires you to define a getRouteKeyName() method on the model like so:

<?php

class Post extends Model
{
    /**
     * Get the route key for the model.
     *
     * @return string
     */
    public function getRouteKeyName()
    {
        return 'slug';
    }
}


You can use the below route binding when you have multiple routes that you want to bind differently.

For example, the frontend route uses slugs to display posts and backend admin uses ids to manage posts:


Route::get('/posts/{post:slug}', function (Post $post) {
    // ...
});

// Or you could use the default `{post}` here...
Route::get('/admin/posts/{post:id}/edit', function (Post $post) {
    // ...
});


Thanks for reading.





kizinho

I am a software developer, like meeting people and love blogging, that's why I developed naijacrawl because that's what I love doing.

Continue Reading
Click To Comment

BE First To Comment


    Leave a Reply

    Your email address will not be published. Required fields are marked *

    Laravel 5.8.8 Released (bugs fixed and new features )

    kizinho

    Published

    on

    Laravel 5.8.8 Released (bugs fixed and new features )
    Photo: Naijacrawl

    The Laravel team released Laravel 5.8.8 yesterday with a new query builder method along with the latest fixes and changes in the 5.8 branch.

     

    First, a new Builder::forPageBeforeId() method was added to compliment an existing forPageAfterId().

     

    These methods are useful to query for records before or after a given record. In the pull request author Tim MacDonald illustrates the following example to get the records around a “focused” post:

    $posts = new Collection;
    
    $posts = $posts->concat(ChatPost::forPageBeforeId(15, $focused->id)->get()->reverse());
    
    $posts = $posts->push($focused);
    
    $posts = $posts->concat(ChatPost::forPageAfterId(15, $focused->id)->get());

     

     

    You can see the full list of fixes below, and the whole difference  between 5.8.7 and 5.8.8 on GitHub.

     

    The full release notes for Laravel 5.8 are available in the GitHub 5.8 changelog:

     

    v5.8.8

    Added Added Illuminate\Database\Query\Builder::forPageBeforeId() method (#28011)


    Fixed

    BelongsToMany::detach() with custom pivot class (#27997)

    Fixed incorrect event namespace in generated listener by event:generate command (#28007)

     

    Fixed unique validation without ignored column (#27987)


    Changed

     

    Added parameters argument to resolve helper (#28020) Don’t add the path only if path is empty in compiled view (#27976)

     

    Refactoring

    Refactoring of env() helper (#27965)

    Continue Reading

    How to Create Rest API Authentication with Laravel 5.6 and 5.7 using Passport (source code available)

    kizinho

    Published

    on

      How to Create Rest API Authentication with Laravel 5.6 and 5.7 using Passport (source code available)
    Photo: Naijacrawl

    You will learn how  to Create Rest API Authentication with Laravel 5.6 and 5.7 using Passport  after going through this article.

     

    Step 1. Install Laravel

     

    In first step, we require to get fresh Laravel application using below command, So open your terminal or command prompt and run below command:

     

    laravel new auth

     

    Step 2. Install Laravel Passport Package

     

    Laravel Passport provides a full OAuth2 server implementation for your Laravel application in a matter of minutes.

    composer require laravel/passport

     

    Step 3. Run Migration

     

    The Passport migrations will create the tables your application needs to store clients and access tokens.

    php artisan migrate

     

    Step 4. Generate keys

     

    This command will create the encryption keys needed to generate secure access tokens. In addition, the command will create “personal access” and “password grant” clients which will be used to generate access tokens:

    php artisan passport:install

     

    After running this command, add the Laravel\Passport\HasApiTokens trait to your App\Usermodel. This trait will provide a few helper methods to your model which allow you to inspect the authenticated user's token and scopes:

     

    Step 5. Passport Config

     

    Next, you should call the Passport::routes method within the boot method of your AuthServiceProvider. This method will register the routes necessary to issue access tokens and revoke access tokens, clients, and personal access tokens:

     

     'App\Policies\ModelPolicy',
        ];
        /**
         * Register any authentication / authorization services.
         *
         * @return void
         */
        public function boot()
        {
            $this->registerPolicies();
            Passport::routes();
        }
    }

    Finally, in your config/auth.php configuration file, you should set the driver option of the api authentication guard to passport. This will instruct your application to use Passport's TokenGuard when authenticating incoming API requests:

     

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
    ],

     

     

    Step 6. Create API Routes

     

    We will create api routes. Laravel provide routes/api.php file for write web services route. So, let’s add new route on that file.

     

     'auth'
    ], function () {
        Route::post('login', 'AuthController@login');
        Route::post('signup', 'AuthController@signup');
      
        Route::group([
          'middleware' => 'auth:api'
        ], function() {
            Route::get('logout', 'AuthController@logout');
            Route::get('user', 'AuthController@user');
        });
    });

     

    Step 7: Create Controller

     

    In last step we have to create new controller and four api method. So let’s create AuthController and put bellow code:

     

    validate([
                'name' => 'required|string',
                'email' => 'required|string|email|unique:users',
                'password' => 'required|string|confirmed'
            ]);
            $user = new User([
                'name' => $request->name,
                'email' => $request->email,
                'password' => bcrypt($request->password)
            ]);
            $user->save();
            return response()->json([
                'message' => 'Successfully created user!'
            ], 201);
        }
      
        /**
         * Login user and create token
         *
         * @param  [string] email
         * @param  [string] password
         * @param  [boolean] remember_me
         * @return [string] access_token
         * @return [string] token_type
         * @return [string] expires_at
         */
        public function login(Request $request)
        {
            $request->validate([
                'email' => 'required|string|email',
                'password' => 'required|string',
                'remember_me' => 'boolean'
            ]);
            $credentials = request(['email', 'password']);
            if(!Auth::attempt($credentials))
                return response()->json([
                    'message' => 'Unauthorized'
                ], 401);
            $user = $request->user();
            $tokenResult = $user->createToken('Personal Access Token');
            $token = $tokenResult->token;
            if ($request->remember_me)
                $token->expires_at = Carbon::now()->addWeeks(1);
            $token->save();
            return response()->json([
                'access_token' => $tokenResult->accessToken,
                'token_type' => 'Bearer',
                'expires_at' => Carbon::parse(
                    $tokenResult->token->expires_at
                )->toDateTimeString()
            ]);
        }
      
        /**
         * Logout user (Revoke the token)
         *
         * @return [string] message
         */
        public function logout(Request $request)
        {
            $request->user()->token()->revoke();
            return response()->json([
                'message' => 'Successfully logged out'
            ]);
        }
      
        /**
         * Get the authenticated User
         *
         * @return [json] user object
         */
        public function user(Request $request)
        {
            return response()->json($request->user());
        }
    }

     

    Now we are ready to run our example so run bellow command to quick run:

    php artisan serve

    Tests

    Now, we can simple test by rest client tools (Postman), So I test it and you can see below screenshots.

     

     Screen shots coming soon

    Thanks for reading 

    Continue Reading

    How to Download Instagram Photo and Video using PHP (easy way)

    kizinho

    Published

    on

    How to Download Instagram Photo and Video using PHP (easy way)
    Photo: Naijacrawl

    Hi folks, this script is really cool for those of you that want to get informations like photos and videos from Instagram, this tool is for you.

     

    Assuming you are working on a project that needs to get data from Instagram just follow these steps and get it done.

     

    Step 1 

    Download this package using the following command 

     

    composer require ayesh/instagram-download

     

    Step 2 

     

    Set your Instagram photo or video URLs as show below 

     

    getDownloadUrl(); // Returns the download URL.
      $type = $client->getType(); // Returns "image" or "video" depending on the media type.
    }
    catch (\InvalidArgumentException $exception) {
      /*
       * \InvalidArgumentException exceptions will be thrown if there is a validation 
       * error in the URL. You might want to break the code flow and report the error 
       * to your form handler at this point.
       */
      $error = $exception->getMessage();
    }
    catch (\RuntimeException $exception) {
      /*
       * \RuntimeException exceptions will be thrown if the URL could not be 
       * fetched, parsed, or a media could not be extracted from the URL. 
       */
      $error = $exception->getMessage();
    }

     

    You are good to go.

     

     

    Features:

     

    1.Validates Instagram URL (domain validation, URL path validation).

     

    2.Uses OG properties to detect the image and video URL.

     

    3.Supports Instagram photos, videos, and Instagram TV videos Verbose error reporting with proper exceptions.

     

    4.Full unit tests No dependencies other than PHP curl extension (which is most likely enabled by already)

     

    This awesome script written by Ayesh, Visit their official github repository and follow for future updates.

     

    Demo

     

    Enjoy.

    Continue Reading

    Latest



    Face of Naijacrawl


    ChukwubuikemSunday ChukwubuikemSunday

    Sunday Chukwubuikem


    Higher - 09061773292

    Trending