# Changing Laravel Version

# 1. Install laravel of version you want

You can apply this to fresh install project or already existing projects.

# 2. Fillup the required variable in .env

Fill the database configuration and mail SMTP server credentials if you want feature for password reset.

# 3. Create and Run Migration

Create Migration to add role feature in User Table OR you can add following line in migration in newly installed version.

Add role to user table

 $table->string('role',10)->default('user');
1

# 4. Create Middleware

Admin

php artisan make:middleware Admin
1

Copy below code to file

		<?php
		namespace App\Http\Middleware;
		use Auth;
		use Closure;
		class Admin
		{
		    /**
		     * Handle an incoming request.
		     *
		     * @param  \Illuminate\Http\Request  $request
		     * @param  \Closure  $next
		     * @return mixed
		     */
		    public function handle($request, Closure $next)
		    {
		        if (Auth::check() && Auth::user()->role == 'admin') {
		            return $next($request);
		        }
		        else {
		            abort(403);
		        }
		    }
		}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

User

 php artisan make:middleware User
1

Copy below code to file

		<?php
		namespace App\Http\Middleware;
		use Auth;
		use Closure;
		class User
		{
		    /**
		     * Handle an incoming request.
		     *
		     * @param  \Illuminate\Http\Request  $request
		     * @param  \Closure  $next
		     * @return mixed
		     */
		    public function handle($request, Closure $next)
		    {
		        if (Auth::check() && Auth::user()->role == 'user') {
		            return $next($request);
		        }
		        else {
		            abort(403);
		        }
		    }
		}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

# 5. Register Middleware

Add bellow code under $routeMiddleware in app>http>Kernel.php

'admin' => 'App\Http\Middleware\Admin',
'user' => 'App\Http\Middleware\User',
1
2

# 6. Create Resource

UserResource

	php artisan make:resource UserResource
1

Copy below code to file

	<?php
	namespace App\Http\Resources;
	use Illuminate\Http\Resources\Json\JsonResource;
	class UserResource extends JsonResource
	{
	    /**
	     * Transform the resource into an array.
	     *
	     * @param  \Illuminate\Http\Request  $request
	     * @return array
	     */
	    public function toArray($request)
	    {
	        return [
	            'id' => $this->id,
	            'name' => $this->name,
	            'email' => $this->email,
	            'role' => $this->role,
	            'verified' =>$this->hasVerifiedEmail(),
	            'created_at' => $this->created_at,
	            'updated_at' => $this->updated_at,
	        ];
	    }
	}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

# 7. Add Helper Function

Create helpers.php inside app folder and put below code

full_text_search

	use Illuminate\Support\Arr;
	use Illuminate\Support\Str;

	function full_text_search($original , $search ,$except  ){
    $keys = array_keys($original->toArray()[0]);
    $filtered_keys = Arr::except($keys, $except);
    $collection = $original->filter(function ($item) use($filtered_keys,$search) {
        foreach ($filtered_keys as $key){
            if(Str::contains(str::lower($item[$key]),str::lower($search)) == true){
                return $item ;
            }
        }
    });
    return $collection->values()->all();
	}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

paginate

	use Illuminate\Database\Eloquent\Collection;
	use Illuminate\Pagination\LengthAwarePaginator;
	use Illuminate\Pagination\Paginator;
		function paginate($items, $perPage = 15, $page = null, $options = [])
	{
	    $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
	    $items = $items instanceof Collection ? $items : Collection::make($items);
	    return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
	}

1
2
3
4
5
6
7
8
9
10

# 7. Autoload Helper File

Add bellow code under autoload in composer.json

  "files": [
            "app/helpers.php"
        ]
1
2
3

# 8. Create Rule

MatchOldPassword

	php artisan make:rule MatchOldPassword
1

Copy below code to file

	<?php

	namespace App\Rules;

	use Illuminate\Support\Facades\Auth;
	use Illuminate\Support\Facades\Hash;
	use Illuminate\Contracts\Validation\Rule;

	class MatchOldPassword implements Rule
	{
	    /**
	     * The user instance.
	     *
	     * @var \App\User
	     */


	    /**
	     * Determine if the validation rule passes.
	     *
	     * @param  string  $attribute
	     * @param  mixed  $value
	     * @return bool
	     */
	    public function passes($attribute, $value)
	    {
	        return Hash::check($value, Auth::user()->password);
	    }

	    /**
	     * Get the validation error message.
	     *
	     * @return string
	     */
	    public function message()
	    {
	        return 'The :attribute is incorrect.';
	    }
	}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

# 9. Create Controller

UsersController

	php artisan make:controller Api/UsersController
1

Copy below code to file

	<?php
	namespace App\Http\Controllers\Api;
	use App\User;
	use Illuminate\Http\Request;
	use App\Http\Controllers\Controller;
	use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
	use Illuminate\Http\Response;
	use Validator;
	use App\Http\Resources\UserResource;
	class UsersController extends Controller
	{
	    /**
	     * Create a new controller instance.
	     *
	     * @return void
	     */
	    public function __construct()
	    {
	        $this->middleware('admin');
	    }
	    /**
	     * Display a listing of the resource.
	     *
	     * @param Request $request
	     * @return AnonymousResourceCollection
	     */
	    public function index(Request $request)
	    {
	        /*this will be always on the latest*/
	        $result = User::orderBy('created_at','desc')->get();

	        if(isset($request->search) ) {
	            $result = full_text_search($result, $request->search, ["id", "created_at", "updated_at", "email_verified_at"]);
	        }

	        return UserResource::collection(paginate($result , $request->itemsPerPage , $request->page));

	    }

	    /**
	     * Update the specified resource in storage.
	     *
	     * @param Request $request
	     * @param $id
	     * @return UserResource
	     */
	    public function update(Request $request,  $id)
	    {
	        $validation = Validator::make($request->all(), [
	            'name' => 'required|min:3',
	            'email' => 'required|email|unique:users,email,'.$id,
	            'role' => 'required'
	        ]);


	        if ($validation->fails()) {
	            return response()->json($validation->errors(),422);

	        }


	        $user = User::findOrFail($id);
	        $user->fill($request->all())->save();

	        $return = ["status" => "Success",
	            "error" => [
	                "code" => 201,
	                "errors" => 'Deleted'
	            ]];
	        return response()->json($return, 201);
	    }

	    /**
	     * Remove the specified resource from storage.
	     *
	     * @param $id
	     * @return Response
	     */
	    public function destroy($id)
	    {
	        User::whereId($id)->delete();
	        $return = ["status" => "Success",
	            "error" => [
	                "code" => 200,
	                "errors" => 'Deleted'
	            ]];
	        return response()->json($return, 200);
	    }
	}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90

ProfileController

	php artisan make:controller Api/ProfileController
1

Copy below code to file

<?php

	namespace App\Http\Controllers\Api;

	use App\Http\Controllers\Controller;
	use App\Http\Resources\UserResource;
	use App\Rules\MatchOldPassword;
	use App\User;
	use Illuminate\Http\JsonResponse;
	use Illuminate\Http\Request;
	use Illuminate\Support\Facades\Auth;
	use Illuminate\Support\Facades\Hash;
	use Validator;


	class ProfileController extends Controller
	{

	    /**
	     * Create a new controller instance.
	     *
	     * @return void
	     */
	    public function __construct()
	    {
	        $this->middleware('auth');
	    }


	    /**
	     * @return UserResource
	     */
	    public function getMe()
	    {
	        return new UserResource(Auth::user());
	    }


	    /**
	     * Update the specified resource in storage.
	     *
	     * @param Request $request
	     * @param $id
	     * @return UserResource
	     */
	    public function changeEmail(Request $request)
	    {
	        $validation = Validator::make($request->all(), [
	            'email' => 'required|email|unique:users,email,'.Auth::id(),
	        ]);


	        if ($validation->fails()) {
	            return response()->json($validation->errors(), 422);

	        }


	        User::find(Auth::id())->update(['email' => $request->email]);

	        Auth::logout();
	        $return = ["status" => "Success",
	            "message" => 'Email updated!'
	        ];
	        return response()->json($return, 200);

	    }

	    /**
	     * @param Request $request
	     * @return JsonResponse
	     */
	    public function changePassword(Request $request)
	    {
	        $validation = Validator::make($request->all(), [
	            'current' => ['required', new MatchOldPassword],
	            'password' => 'required|confirmed'
	        ]);


	        if ($validation->fails()) {
	            return response()->json($validation->errors(), 422);

	        }


	        User::find(Auth::id())->update(['password' => Hash::make($request->password)]);
	        Auth::logout();
	        $return = ["status" => "Success",
	            "message" => 'Password updated!'
	        ];
	        return response()->json($return, 200);


	    }
	}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97

# 10. Add route to web.php


Route::get('/api', function (){
    return null;
});

Route::namespace('Api')->prefix('api')->name('api.')->group(function () {

    /*Admin Route*/
    Route::resource('/users', 'UsersController', ['except' => ['show', 'create', 'store']]);


    /*User Route*/
    Route::get('/profile/get-me', 'ProfileController@getMe')->name('get.profile');
    Route::post('/profile/change-password', 'ProfileController@changePassword')->name('change.password');
    Route::post('/profile/change-email', 'ProfileController@changeEmail')->name('change.email');
});

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 11. Replace Home View with below code

<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <script src="{{ asset('js/app.js') }}" defer></script>

    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    <link href='https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900|Material+Icons' rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/@mdi/[email protected]/css/materialdesignicons.min.css" rel="stylesheet">

</head>
<body>
<div id="app">
    <main-app></main-app>
</div>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

# 13. Add Admin Creation command

Add Function to user model

Add createAdmin() and adminExists() to the user model. createAdmin() method persists the admin details to the database. adminExists() checks if a super admin exists.


    /**
     * Checks if user is a super admin
     *
     * @return boolean
     */
    public function isAdmin(): bool
    {
        if ($this->role == 'admin') {
            return true;
        }
    }

    /**
     * Create admin.
     *
     * @param array $details
     * @return array
     */
    public function createAdmin(array $details): self
    {
        $user = new self($details);
        if (!$this->adminExists()) {
            $user->role = 'admin';
        }
        $user->save();
        return $user;
    }

    /**
     * Checks if super admin exists
     *
     * @return integer
     */
    public function adminExists(): int
    {
        return self::where('role', 'admin')->count();
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

Add RegisterAdminCommand Command

php artisan make:command RegisterAdminCommand

1
2

Copy below code to file

<?php

namespace App\Console\Commands;

use App\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Hash;

class RegisterAdminCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'register:admin';
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Register  admin';

    /**
     * User model.
     *
     * @var object
     */
    private $user;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(User $user)
    {
        parent::__construct();
        $this->user = $user;
    }


    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $details = $this->getDetails();
        $admin = $this->user->createAdmin($details);
        $this->display($admin);
    }


    /**
     * Ask for admin details.
     *
     * @return array
     */
    private function getDetails(): array
    {
        $details['name'] = $this->ask('Name');
        $details['email'] = $this->ask('Email');
        $details['password'] = $this->secret('Password');
        $details['confirm_password'] = $this->secret('Confirm password');
        while (!$this->isValidPassword($details['password'], $details['confirm_password'])) {
            if (!$this->isRequiredLength($details['password'])) {
                $this->error('Password must be more that six characters');
            }
            if (!$this->isMatch($details['password'], $details['confirm_password'])) {
                $this->error('Password and Confirm password do not match');
            }
            $details['password'] = $this->secret('Password');
            $details['confirm_password'] = $this->secret('Confirm password');
        }
        $details['password'] = Hash::make($details['password']);

        return $details;
    }

    /**
     * Display created admin.
     *
     * @param array $admin
     * @return void
     */
    private function display(User $admin): void
    {
        $headers = ['Name', 'Email', 'Super admin'];
        $fields = [
            'Name' => $admin->name,
            'email' => $admin->email,
            'admin' => $admin->isAdmin()
        ];
        $this->info('Admin created');
        $this->table($headers, [$fields]);
    }

    /**
     * Check if password is vailid
     *
     * @param string $password
     * @param string $confirmPassword
     * @return boolean
     */
    private function isValidPassword(string $password, string $confirmPassword): bool
    {
        return $this->isRequiredLength($password) &&
            $this->isMatch($password, $confirmPassword);
    }

    /**
     * Check if password and confirm password matches.
     *
     * @param string $password
     * @param string $confirmPassword
     * @return bool
     */
    private function isMatch(string $password, string $confirmPassword): bool
    {
        return $password === $confirmPassword;
    }

    /**
     * Checks if password is longer than six characters.
     *
     * @param string $password
     * @return bool
     */
    private function isRequiredLength(string $password): bool
    {
        return strlen($password) > 6;
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136