You are on page 1of 19

CREATE PROJECT:

METHOD 1:

composer global require laravel/installer (Install the


laravel/installer globally)

larvel new project_name (create new


project)

composer global remove laravel/installer (Remove the


laravel/installer)

METHOD 2:

composer create-project --prefer-dist laravel/laravel projectname


(Create the new project)

===================================================================================
======================

MIGRATION:

php artisan migrate (migrate all the


tables)

php artisan migrate:reset (reset all the


tables)

php artisan make:migration create_tablename_table (crete new


table)

php artisan migrate:rollback (move to the last


step)

php artisan migrate:rollback --step 2 (last 2


step)

php artisan migrate:refresh (first rollback


then migrate)

php artisan migrate:status (check cuurent


status of tables)

php artisan migrate --path=\relative path of table

php artisan make:migration drop_tablename_table (drop the


table)

===================================================================================
======================

SEEDERS:

php artisan make:seeder seedername (create seeder


file)

DB::table('table_name')->insert( [
'name'=>Str::random(10),

] );

php artisan db:seed --class=class_name_of_seeder

===================================================================================
======================_

FACTORIES:

create table

create seeder and factory of table

In the factory definition function write lines as

return [

'name' => $this->faker->name,

];

In the seeder run function write lines as

public function run()

Student::factory()->count(10)->create();

php artisan db:seed --class=class_name_of_seeder

===================================================================================
======================

AUTH:

METHOD 1:

composer require laravel/ui

php artisan ui vue --auth

npm install

npm run dev

npm run development

METHOD 2:

composer require laravel/breeze

php artisan breeze:install

npm install
npm run dev

METHOD 3:

composer require laravel/ui

php artisan ui:auth

===================================================================================
======================

CACHE:

php artisan route:clear (Clear the route cache)

php artisan cache:clear (Clear the cache)

php artisan optimize:clear (clear the cache)

===================================================================================
======================

GITHUB:

git config --global user.name ------------

git config --global user.name

git config --global user.email -----------

git config --global user.email

code . (open vs code)

git init (Initialize empty git


repo)

ls -lart (Display all Files)

touch contact.html (Create file)

git status (Display current status


of files)

git add -A (Add all files)

git add . (Add all files)

git add contact.html (Add specific


files)

git commit -m "Message comes here" (Commit the


changes)

git checkout contact.html (Move to the last


updated values in the contact file)

git checkout -f (for all files move to


backward step)

git log (show all commits


details and auther who commit it)

git log -p -1 (show last 1


commit)

git diff (Compared changes with


commit)

git diff --staged (compared commit


with last staged)

git commit -a -m "Message" (Add and commit)

git rm --cached waste.html (Move file from


commit to unattached)

git rm waste.html (Delete file)

touch .gitignore (Files that git ignore)

git branch feature1 (Create copy of


master branch)

git checkout feature1 (Switch to


feature1 branch)

git checkout -b feature1 (Create copy of


master and switch to new branch)

git merge feature1 (Merge feature1


branch with master)

git branch (Check the current


branch)

git mkdir folder (Create a new folder)

cd d: (Jump into the d


directory)

===================================================================================
======================

HOW TO LINK TO THE GITHUB:

git remote add origin repo_link

git push -u origin branch_name

git push

git remote (Show list name like origin)

git remote -v (Show url for


fetch/pull/push)
HOW TO DOWNLOAD THE PROJECT FROM GITHUB:

METHOD 1:

download the zip file

composer install/update (In most cases we use


install)

npm install

npm run dev

cp .env.example .env (Create copy


of .env.example)

php artisan key:generate (Generate the key)

setup the database

METHOD 2:

git clone http_link . (Clone the git repo)

git clone ssh_link (Clone the git repo)

===================================================================================
======================

HOW TO UPLOAD PDF FILE ON THE DATABSE AND SEARCH THE KEY WORD FROM IT:

php artisan make:model File -mc (Make Migration,


Model, and controller)

create fields in the table

Schema::create('files', function (Blueprint $table) {


$table->id();
$table->string('orig_filename', 100)->nullable();
$table->string('mime_type', 50)->nullable();
$table->bigInteger('filesize');
$table->text('content')->nullable();
$table->timestamps();
});

run the command

composer require smalot/pdfparser

create a blade file

<x-app-layout>
<x-slot name="header">
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
{{ __('Upload File') }}
</h2>
</x-slot>
{{-- ex using component x-component_name --}}
@if (Session::has('success'))
<x-success>
{{ session()->get('success') }}
</x-success>
@endif
@if (Session::has('error'))
<x-error>
{{ session()->get('error') }}
</x-error>
@endif

<div class="py-12">
<div class="max-w-5xl mx-auto sm:px-6 lg:px-8">
<div class="bg-white overflow-hidden shadow-sm sm:rounded-
lg">
<div class="p-6 bg-white border-b border-gray-200">
<form action="{{ route('file.store') }}"
enctype="multipart/form-data"
method="POST">
@csrf
<div class="mb-2"> <span>Attachments</span>
<div
class="relative h-40 rounded-lg border-
dashed border-2 border-gray-200 bg-white flex justify-center items-center
hover:cursor-pointer">
<div class="absolute">
<div class="flex flex-col items-
center "> <i
class="fa fa-cloud-upload
fa-3x text-gray-200"></i>
<span class="block text-gray-
400 font-normal">Attach
you files here</span> <span
class="block text-gray-400
font-normal">or</span>
<span class="block text-blue-
400 font-normal">Browse
files</span>
</div>
</div>
<input type="file" class="h-full w-full
opacity-0" name="file" >
</div>
</div>
<div class="mt-3 text-center pb-3">
<button type="submit"
class="w-full h-12 text-lg w-32 bg-
blue-600 rounded text-white hover:bg-blue-700">
Save
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</x-app-layout>
create the routes

Route::get('file', [FileController::class, 'index'])->name('file');


Route::post('file', [FileController::class, 'store'])-
>name('file.store');

import the header files/class

use Smalot\PdfParser\Parser;

create a store function in the controller

$file = $request->file;

$request->validate([
'file' => 'required|mimes:pdf',
]);

// use of pdf parser to read content from pdf


$fileName = $file->getClientOriginalName();
// $file->move(public_path('pdf'), $fileName);
$pdfParser = new Parser();
$pdf = $pdfParser->parseFile($file->path());
$content = $pdf->getText();
$upload_file = new File;
$upload_file->orig_filename = $fileName;
$upload_file->mime_type = $file->getMimeType();
$upload_file->filesize = $file->getSize();
$upload_file->content = $content;
$upload_file->save();
return redirect('search')->with('success', 'File uploaded
successfullly...');

create a show function in the controller

$search = $request['search'] ?? "";


if ($search != "") {
$file = File::where('content', 'LIKE', "%$search%")->get();
}
$text = strtolower($file);
$find = strtolower($request->search);
$pos = strpos($text, $find);
if ($pos == true) {

$message = "String was found";


return view('data', compact('file'));
} else {

echo "String not found.";


}

===================================================================================
======================

HOW TO SEND MAIL IN LARAVEL:

METHOD 1:

STEP 1:
setup the .env file
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=mygoogle@gmail.com
MAIL_PASSWORD=rrnnucvnqlbsl
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=mygoogle@gmail.com
MAIL_FROM_NAME="${APP_NAME}"

STEP 2:
Create Mail
php artisan make:mail MyTestMail

STEP 3:
setup the mytestmail file

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class MyTestMail extends Mailable


{
use Queueable, SerializesModels;

public $details;

/**
* Create a new message instance.
*
* @return void
*/
public function __construct($details)
{
$this->details = $details;
}

/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->subject('Mail from ItSolutionStuff.com')
->view('emails.myTestMail');
}
}

STEP 4:
Create Blade View mytestmail and write the code
<!DOCTYPE html>
<html>
<head>
<title>ItsolutionStuff.com</title>
</head>
<body>
<h1>{{ $details['title'] }}</h1>
<p>{{ $details['body'] }}</p>

<p>Thank you</p>
</body>
</html>

STEP 5:
Add Route or controller function

Route::get('send-mail', function () {

$details = [
'title' => 'Mail from ItSolutionStuff.com',
'body' => 'This is for testing email using smtp'
];

\Mail::to('your_receiver_email@gmail.com')->send(new \App\Mail\
MyTestMail($details));

dd("Email is Sent.");
});

METHOD 2:

STEP 0:
setup the .env file
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USERNAME=email
MAIL_PASSWORD=password
MAIL_ENCRYPTION=ssl
MAIL_FROM_ADDRESS=email
MAIL_FROM_NAME="${APP_NAME}"

STEP 1:
creates the routes

Route::view('contact', 'contactform')->name('contactform');
Route::post('send', [ContactController::class, 'send'])-
>name('send_email');

STEP 2:
creates the blade fille contactform.blade.php

<body>
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3 mt-5">
<h4>Contact Us</h4>
<hr>
<form action="{{ route('send_email') }}" method="POST">
@csrf
<div class="form-group">
<label for="name"
class="form-label">Name</label>
<input type="text" name="name" id="name"
class="form-control" placeholder="Enter Your Name"
value="{{ old('name') }}">
@error('name')
<span class="text-danger">{{ $message }}</span>
@enderror
</div>
<div class="form-group">
<label for="email"
class="form-label">Email</label>
<input type="email" name="email" id="email"
class="form-control" placeholder="Enter Your Email"
value="{{ old('email') }}">
@error('email')
<span class="text-danger">{{ $message }}</span>
@enderror
</div>
<div class="form-group">
<label for="subject" class="form-
label">Subject</label>
<input type="text" name="subject" id="subject"
class="form-control" placeholder="Enter Subject"
value="{{ old('subject') }}">
@error('subject')
<span class="text-danger">{{ $message }}</span>
@enderror
</div>
<div class="form-group">
<label for="message" class="form-
label">Message</label>
<textarea name="message" class="form-control"
id="message" cols="4"
rows="4">{{ old('message') }}</textarea>
@error('message')
<span class="text-danger">{{ $message }}</span>
@enderror
</div>
<button class="btn btn-primary">Send</button>
</form>
</div>
</div>
</div>
</body>

STEP 4:
create the controller
class ContactController extends Controller
{
public function send(Request $request)
{
$request->validate([
'name' => 'required',
'email' => 'required|email',
'subject' => 'required',
'message' => 'required'
]);

if ($this->isOnline()) {
$mail_data = [
'recipient' => 'mustajabahmed02@gmail.com',
'fromEmail' => $request->email,
'fromName' => $request->name,
'subject' => $request->subject,
'body' => $request->message
];
Mail::send('email-template', $mail_data, function
($message) use ($mail_data) {
$message->to($mail_data['recipient'])
->from($mail_data['fromEmail'],
$mail_data['fromName'])
->subject($mail_data['subject']);
});

return redirect()->back()->with('success', 'Email Sent!');


} else {
return "Not Connected";
}
}

public function isOnline($site = "https://www.youtube.com/")


{
if (@fopen($site, 'r')) {
return true;
} else {
return false;
}
}
}

STEP 5:
create another blade file in which write the data which you want to display
in the mail
email-template.blade.php
{{ $body }}

===================================================================================
======================

HOW TO VERIFY USER AFTER REGISTERATION:

STEP 0:
Create Auth

STEP 1:
Goto the user.php model and implements the MustVerifyEmail and import class

STEP 2:
Goto the Config/fortify.php and in the features array add

Features::emailVerification(),

If the fortify.php folder not found then create ther fortify folder

1. composer require laravel/fortify


2. php artisan vendor:publish --provider="Laravel\Fortify\
FortifyServiceProvider"
3. php artisan migrate

STEP 3:
Goto the .env file and make the changes

MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USERNAME=email
MAIL_PASSWORD=password
MAIL_ENCRYPTION=ssl
MAIL_FROM_ADDRESS=email
MAIL_FROM_NAME="This is my first laravel mail"

===================================================================================
======================

HOW TO CREATE SIGNIN WITH GOOGLE, FACEBOOK ETC..

STEP 1:
create the project

STEP 2:
Create the auth

STEP 3:
Change the design of Login page

STEP 4:
install the socialized package

composer require laravel/socialite

STEP 5:
we will login with google, facebook, github

STEP 6:
goto the config/services and add some code

'google' => [
'client_id' => env('GOOGLE_CLIENT_ID'),
'client_secret' => env('GOOGLE_CLIENT_SECRET'),
'redirect' => 'http://example.com/callback-url',
],

'facebook' => [
'client_id' => env('FACEBOOK_CLIENT_ID'),
'client_secret' => env('FACEBOOK_CLIENT_SECRET'),
'redirect' => 'http://example.com/callback-url',
],

'github' => [
'client_id' => env('GITHUB_CLIENT_ID'),
'client_secret' => env('GITHUB_CLIENT_SECRET'),
'redirect' => 'http://example.com/callback-url',
],

STEP 7:
add routes
// Google Login
Route::get('login/google', [LoginController::class,
'redirectToGoogle'])->name('login.google');
Route::get('login/google/callback', [LoginController::class,
'handleGoogleCallback']);

// Facebook Login
Route::get('login/facebook', [LoginController::class,
'redirectToFaceook'])->name('login.facebook');
Route::get('login/facebook/callback', [LoginController::class,
'handleFacebookCallback']);

// Github Login
Route::get('login/github', [LoginController::class,
'redirectToGithub'])->name('login.github');
Route::get('login/github/callback', [LoginController::class,
'handleGithubCallback']);

STEP 8:
put url in the login button of google, facebook, github

STEP 9:
put id and secret variables for each app in the .env file

STEP 10:
change the redirect link for each app in the config/service file

STEP 11:
create the functions for each app which are define in the routes

// Google Login
public function redirectToGoogle()
{
return Socialite::driver('google')->redirect();
}
// Google Callback
public function handleGoogleCallback()
{
$user = Socialite::driver('google')->user();
}

same for facebook and github and other platforms

STEP 12:
goto the google api website and create app for google, facebook and github

STEP 13:
now we add extra fields to users table

$table->string('provider_id')->nullable();
$table->string('avatar')->nullable();

STEP 14:
run the migration

STEP 15:
Will create a method which will create new user or login existing user in the
LoginController
STEP 16:
add user avatar beside of user name

STEP 17:
now test with google signing

===================================================================================
=======================================

HOW TO UPLOAD IMAGE IN THE DATABASE:

STEP 1:
in the controller function write the code

$file = $request->file('image');
$filename = $file->getClientOriginalName();
$file->move(public_path('Image'), $filename);
$card->image = $filename;

===================================================================================
=======================================

DATA SCRAPING:

composer require fabpot/goutte

use Goutte\Client;

===================================================================================
=======================================

Make REST API AUTHENTICATION in LARAVEL 9 USING LARAVEL SANCTUM:

STEP 1:
Install via composer

composer require laravel/sanctum

STEP 2:
Publish the Sanctum Service Provider

php artisan vendor:publish --provider="Laravel\Sanctum\


SanctumServiceProvider"

STEP 3:
Migrate The Database

php artisan migrate

STEP 4:
User HasApiTokens Trait in App\Models\User

STEP 5:
Create AuthController to handle all authentication realted to API

php artisan make:controller Api\AuthController

STEP 6:
In routes\api.php file update the API

Route::post('/auth/register', [AuthController::class, 'createUser']);

Route::post('/auth/login', [AuthController::class, 'loginUser']);

STEP 7:
Now update AuthContoller with createuser and loginUser
public function createUser(Request $request)
{
try {
//Validated
$validateUser = Validator::make($request->all(),
[
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required'
]);

if($validateUser->fails()){
return response()->json([
'status' => false,
'message' => 'validation error',
'errors' => $validateUser->errors()
], 401);
}

$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password)
]);

return response()->json([
'status' => true,
'message' => 'User Created Successfully',
'token' => $user->createToken("API TOKEN")-
>plainTextToken
], 200);

} catch (\Throwable $th) {


return response()->json([
'status' => false,
'message' => $th->getMessage()
], 500);
}
}

public function loginUser(Request $request)


{
try {
$validateUser = Validator::make($request->all(),
[
'email' => 'required|email',
'password' => 'required'
]);

if($validateUser->fails()){
return response()->json([
'status' => false,
'message' => 'validation error',
'errors' => $validateUser->errors()
], 401);
}

if(!Auth::attempt($request->only(['email', 'password']))){
return response()->json([
'status' => false,
'message' => 'Email & Password does not match with
our record.',
], 401);
}

$user = User::where('email', $request->email)->first();

return response()->json([
'status' => true,
'message' => 'User Logged In Successfully',
'token' => $user->createToken("API TOKEN")-
>plainTextToken
], 200);

} catch (\Throwable $th) {


return response()->json([
'status' => false,
'message' => $th->getMessage()
], 500);
}
}
}

STEP 8:
Now test in the postman or we can also create the crud application.

===================================================================================
=======================================

Stripe:

Stripe::setApiKey(env('STRIPE_SECRET'));
$session = \Stripe\Checkout\
Session::create([
'line_items' => [
[
'price_data' =>[
'currency'=>$booking->currency,
'product_data'=>[
'name'=>'Service'
],

'unit_amount'=>$amountInCents,
],
'quantity' => 1,
]
],
'mode' =>
'payment',
'success_url' =>
url('stripe/success/'.$booking->id),
'cancel_url' =>
url('customer/bookings'),
]);
return redirect()-
>away($session->url);
Also available on the official documentation

===================================================================================
=======================================

step1: composer require maatwebsite/excel

step2: -----> config/app.php 'providers' => [


// ...
Maatwebsite\Excel\ExcelServiceProvider::class,
],

step3: -----> config/app.php 'aliases' => [


// ...
'Excel' => Maatwebsite\Excel\Facades\
Excel::class,
],
step4: run -----> composer dump-autoload

step5: php artisan config:clear

step6: buttton add in view file ------> <div class="col-md-6"> <!-- Right Column
-->
<form action="{{ route('readExcelData')
}}" method="POST"
enctype="multipart/form-data">
@csrf
<div class="mb-1">
<label for="import-doctor"
class="btn btn-success">
Import Doctor & Clinics
File
<input type="file"
id="import-doctor" name="excel_file"
style="display: none;"
required>
</label>
</div>
<div class="mb-1">
<button type="submit"
class="btn btn-primary">Upload Excel
File</button>
</div>
</form>
<div>

step7: php artisan make:controller ExcelController


step8: Route::post('admin/export-excel', [ExcelController::class,
'readExcelData'])->name('readExcelData');
step9: php artisan make:import ExcelImport
step10: add code in impoert file------>

<?php

namespace App\Imports;

use App\Models\Clinic;
use App\Models\DrInfo;
use App\Models\User;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;

class ExcelImport implements ToCollection


{
public function collection(Collection $collection)
{
// Initialize an array to store clinic names
$clinics = [];

// Set the row number for clinic names (e.g., 1st row)
$clinicRow = 2;

// Extract clinic names from the specified row


$clinicNames = $collection->get($clinicRow - 1);

foreach ($clinicNames as $clinicName) {


if (!empty($clinicName)) {
// Insert clinic names into the clinics table
$clinic = Clinic::firstOrCreate(['name' => $clinicName]);
$clinics[] = $clinic;
}
}

// Initialize an array to store user data grouped by clinics


$clinicUserData = [];

// Loop through the remaining rows (users) and store them by clinic
foreach ($collection->slice($clinicRow) as $row) {
foreach ($row as $clinicIndex => $userName) {
if (!empty($userName)) {
// Get the current clinic and user
$clinic = $clinics[$clinicIndex];
$user = User::create(['name' => $userName]);

// Add user data to the corresponding clinic


$clinicUserData[$clinic->id][] = $user->id;
}
}
}

// Loop through clinic data and create dr_info entries


foreach ($clinicUserData as $clinicId => $userIds) {
foreach ($userIds as $userId) {
DrInfo::create(['clinic_id' => $clinicId, 'user_id' => $userId]);
}
}
}
}

===================================================================================
===========================

step1:follow all steps using this link (https://chatify.munafio.com/installation)


step2:change in .env file-----> BROADCAST_DRIVER=pusher
step3:uncommint this line (App\Providers\BroadcastServiceProvider::class,)------->
path---->config/app.php
step4: if pusher error occure then you ---> add ---> DEBUGBAR_ENABLED=false---
>in .env file otherwise not add

===================================================================================
===========================

You might also like