<?phpuseIlluminate\Database\Migrations\Migration;useIlluminate\Database\Schema\Blueprint;useIlluminate\Support\Facades\Schema;classCreateUsersTableextendsMigration{/** * Run the migrations. * * @returnvoid */publicfunctionup() {Schema::create('users',function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->text('access_token')->nullable(); // ADD THIS COLUMN $table->string('password'); $table->rememberToken(); $table->timestamps(); }); }/** * Reverse the migrations. * * @returnvoid */publicfunctiondown() {Schema::dropIfExists('users'); }}
C:\xampp82\htdocs\lva4\app\Models\User.php
<?phpnamespaceApp\Models;useIlluminate\Contracts\Auth\MustVerifyEmail;useIlluminate\Database\Eloquent\Factories\HasFactory;useIlluminate\Foundation\Auth\Useras Authenticatable;useIlluminate\Notifications\Notifiable;useLaravel\Sanctum\HasApiTokens;classUserextendsAuthenticatable{useHasApiTokens,HasFactory,Notifiable;/** * The attributes that are mass assignable. * * @vararray */protected $fillable = ['name','email','password','access_token'// ADD TOKEN PROPERTY HERE ];/** * The attributes that should be hidden for serialization. * * @vararray */protected $hidden = ['password','remember_token', ];/** * The attributes that should be cast. * * @vararray */protected $casts = ['email_verified_at'=>'datetime', ];}
C:\xampp82\htdocs\lva4\routes\web.php
<?phpuseApp\Http\Controllers\GoogleDriveController;useIlluminate\Support\Facades\Route;/*|--------------------------------------------------------------------------| Web Routes|--------------------------------------------------------------------------|| Here is where you can register web routes for your application. These| routes are loaded by the RouteServiceProvider and all of them will| be assigned to the "web" middleware group. Make something great!|*/Route::get('/',function () {returnview('welcome');});Auth::routes();Route::get('/home', [App\Http\Controllers\HomeController::class,'index'])->name('home');Route::get('google/login', [GoogleDriveController::class,'googleLogin'])->name('google.login');Route::get('google-drive/file-upload', [GoogleDriveController::class,'googleDriveFilePpload'])->name('google.drive.file.upload');
<?phpnamespaceApp\Http\Controllers;useIlluminate\Http\Request;useApp\Models\User;classGoogleDriveControllerextendsController{public $gClient;function__construct() {$this->gClient =new\Google_Client();$this->gClient->setApplicationName('Web client 1'); // ADD YOUR AUTH2 APPLICATION NAME (WHEN YOUR GENERATE SECRATE KEY)$this->gClient->setClientId('710157078117-9t8ppso74lgg3f90nrf24nk8tp8t4ula.apps.googleusercontent.com');$this->gClient->setClientSecret('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');$this->gClient->setRedirectUri('https://lva4.com/google/login');$this->gClient->setDeveloperKey('1KZ5fYZ9McCeMrSr2YE3o10ywODPpTkmN');$this->gClient->setScopes(array('https://www.googleapis.com/auth/drive.file','https://www.googleapis.com/auth/drive' ));$this->gClient->setAccessType("offline");$this->gClient->setApprovalPrompt("force"); }publicfunctiongoogleLogin(Request $request) { $google_oauthV2 =new\Google_Service_Oauth2($this->gClient);if ($request->get('code')) {$this->gClient->authenticate($request->get('code')); $request->session()->put('token',$this->gClient->getAccessToken()); }if ($request->session()->get('token')) {$this->gClient->setAccessToken($request->session()->get('token')); }if ($this->gClient->getAccessToken()) {//FOR LOGGED IN USER, GET DETAILS FROM GOOGLE USING ACCES $user =User::find(1); $user->access_token =json_encode($request->session()->get('token')); $user->save();dd("Successfully authenticated"); } else {// FOR GUEST USER, GET GOOGLE LOGIN URL $authUrl =$this->gClient->createAuthUrl();returnredirect()->to($authUrl); } }publicfunctiongoogleDriveFilePpload() { $service =new\Google_Service_Drive($this->gClient); $user =User::find(1);$this->gClient->setAccessToken(json_decode($user->access_token,true));if ($this->gClient->isAccessTokenExpired()) {// SAVE REFRESH TOKEN TO SOME VARIABLE $refreshTokenSaved =$this->gClient->getRefreshToken();// UPDATE ACCESS TOKEN$this->gClient->fetchAccessTokenWithRefreshToken($refreshTokenSaved);// PASS ACCESS TOKEN TO SOME VARIABLE $updatedAccessToken =$this->gClient->getAccessToken();// APPEND REFRESH TOKEN $updatedAccessToken['refresh_token'] = $refreshTokenSaved;// SET THE NEW ACCES TOKEN$this->gClient->setAccessToken($updatedAccessToken); $user->access_token = $updatedAccessToken; $user->save(); } $fileMetadata =new\Google_Service_Drive_DriveFile(array('name'=>'Webappfix',// ADD YOUR GOOGLE DRIVE FOLDER NAME'mimeType'=>'application/vnd.google-apps.folder' )); $folder = $service->files->create($fileMetadata,array('fields'=>'id'));printf("Folder ID: %s\n", $folder->id); $file =new\Google_Service_Drive_DriveFile(array('name'=>'cdrfile.jpg','parents'=>array($folder->id))); $result = $service->files->create($file,array('data'=>file_get_contents(public_path('Screenshot_1.png')),// ADD YOUR FILE PATH WHICH YOU WANT TO UPLOAD ON GOOGLE DRIVE'mimeType'=>'application/octet-stream','uploadType'=>'media' ));// GET URL OF UPLOADED FILE $url ='https://drive.google.com/open?id='. $result->id;dd($result); }}
Create a new project using the dropdown at the top.
After you enter a name, it takes a few seconds before the project is successfully created on the server.
Make sure you have the project selected at the top.
Then go to Library and click on "Drive API" under "Google Apps APIs".
And then Enable it.
Then, go to "Credentials" and click on the tab "OAuth Consent Screen". Fill in a "Product name shown to users" and Save it. Don't worry about the other fields.
Then go back to Credentials, click the button that says "Create Credentials" and select "OAuth Client ID".
If you want to store files in your Google Drive root directory, then the folder ID can be null. Else go into your Drive and create a folder.
Because Google Drive allows for duplicate names, it identifies each file and folder with a unique ID. If you open your folder, you will see the Folder ID in the URL.