LARAVEL MY CUSTOM FILE

OCTOBER 2 2020


CREATE A NEW LARAVEL PROJECT

    1: E:

    2: cd xamp\htdocs

    3: composer create-project --prefer-dist laravel/laravel test


FOR COMPLETE FRAMWORK DOWNLOAD OF LARAVEL

    composer create-project laravel/laravel test dev-develop


START LARAVEL PROJECT

    go tp the folder project folder

    E:xamp>htdocs>laravel>Blogger (Blogger is project name)(in cmd)

    php artisan serve(starts the laravel framework by default on localhost:8000)


BASIC URL WILL BE

    http://localhost/PROJECT NAME/public/      


REMOVE THE PUBLIC FROM URL

    1- Go to public folder copy htaccess file and past it in root directory(root folder)

    2- then in root of file find server.php copy and paste the file and change the copied filename into index.php  


LARAVEL ASSETS

    composer require laravel/ui

    PRESS ENTER

    php artisan ui bootstrap    

    PRESS ENTER

    npm install

    PRESS ENTER

    npm run dev

    PRESS ENTER


FILE STRUCTURE 

    web.php

    in routes folder


    views.php

    in resourses folder


    assets(css,js,themes)

    in resourses folder


    Controller.php

    in app folder >> in http folder


    Model.php

    in app folder >> in model folder


    Migration in 

    root in database folder >> in migration folder


    Database connection is in

    .env file (in root) 


ROUTING HAVE 4 METHOD

    1- get

    2- post

    3- any

    4- match 


ROUTING CALLS

    

    without parameter

    Route::get('/name',function(){

        $variable = "qasim";

        echo $variable;

    });


    with parameter

    Route::get('/pagename{id}', function ($id) {

        return $id;

    });


    with optional parameter

    yeh optional h if ap url mai id pass nhe krty to by default wo id 1 nhe to jo value do gy wohi aie gi

    Route::get('about/{id?}',function($id=1){

        return $id;

    });    


    agr url mai condition lgni h k sirf url mai number e jae

    http://localhost/laravel-project/public/admin/1

    so


    Route::get('/admin/{id}/', function ( $id) {

        echo "id".$id;

    })->where(['number'=>"[0-9]+"]);


    named routes 

    Basically yeh sirf ak route ko nickname dyny k liya hty hain is ka usage url genrate krny k liya hta h like ak route(url) sy dusray route (url) tk jana

 

    Route::get('Homepage/secondpage',function(){

    echo "home page is here";

    })->name('nickname');

    //yeh ak route h aur us ka nickname route bnya h 


    Route::get('/nextpage',function(){

        echo route('nickname');

    };

    OR

    Route::get('Homepage/Defaultpage',array('as'=>'nickname',function(){

        echo "Home in side default";

    }));


    is sy ap Homepage/secondpage ka url b genrate kr skty hain jis ka code above h aur kisi aur url ya route sy is url py Homepage/secondpage redirect b  ho skty hain jiss ka code below h


    Route::get('/nextpage',function(){

        return redirect()->route('nickname');

    });


    group routing

    mutliple pages ko agr same thing lgni ho ussy group routing sy krty hain like agr humain authentication lgni h session ki phr  hum esy kry gy 


    Route::group(['middleware'=>'Authenticate'],function(){

        Route::get('/', function () {

            return view('welcome');

        });

    });

    is code mai hum ny welcome k page ko authentication lgae h


    agr humary controller folder k ander sub controller folder hain to humain namespace use krni pery gi


    Route::group(['middleware'=>'Authenticate'],'namespace=>'admin',function(){

        Route::get('/', function () {

            return view('welcome');

        });

    });


    aur agr sigle route sy jana ho to

    Route::get('/','Admin.controller@function');


    prefix route url mai special words aa jae ga

    Route::group(['middleware'=>'Authenticate'],'prefix=>'admin',function(){

        Route::get('/',array( 'as'=>'mainpanel',

        function () {

            return view('welcome');

        }));

    });


MAKE A CONTROLLER

    php artisan make:controller customController


    for resourses controller

    php artisan make:controller customController -r


MAKE A MODEL

    php artisan make:model Custom (model name single)    


    for resourses controller

    php artisan make:model Custom -m (model name single)    


MAKE A MIGRATION

    php artisan make:migration create_customs_table (table name plural)   


CONTROLLER


    passing array to view

    public function show(){

        $user=array('qasim',03356,'male','gujrat');

        return view('about',['person'=>$user]);

    }


    OR


    public function show(){

        $user=array('qasim',03356,'male','gujrat');

        return view('about',compact('user'));

    }    


VIEWS

    always save file in 

    pagename.blade.php


    in view

    show data in in view file

    <? $data ?>  (this is this the way is core php)

    Not secured like agr controller mai esa ho


    in controller

    public function showdata(){

        return view('Mainpage')->with('data',"<script>alert('danger');</script>");

    }

    

    inview

    <? $data ?>  alert show ho ga as site can easily b crack


    {{ data }}  (this is used for cleaning the code in blade php)

    Is sy output nhe mai script show ho ga alert nhe jiss sy data secure h

    {!! Data !!}  


    how to use if else if

    @if ()

     @elseif

    @endif


    how to use foreach

    @if(isset()){

        @foreach($data as $row){


        }

    }

    @else{

        No record

    }

    @endif


    combination of if and foreach

    If else and for each k combination ko forelse use krtain hain


    @forelse()


    @empty

    No record 


BLADE TEMPLATING

    basic concept is that k different pages ko same layout ko templating kehty hain

    follow is ka hta h like controller mai page call kiya h addcomment

    addcomment page will call first than addcomment page will call master page


    MASTER PAGE

    layout.blade.php      


    Include function ki trha chlta h like master page jiss main ap ny header footer lga diya hain aur body waly part main changing hogi phr     



    <!DOCTYPE html>

    <html>

    <head>

        <title>Master Page</title>

    </head>

    <body style="background-color: Blue;">


    <p>this is the master page content </p>

    (suppose yahn py navigation aur footer h)


    <div class="container" >


    @yield('bodywork')      //yeh us page ka wo section ka addres bta rha h jahan sy data change h

        

    </div>

    </body>

    </html>


    ADDCOMMENT.page

    addcomment.blade.php

    @extends('layout')  //yeh bta rha h is master page ko extend krna h

    @section('bodywork') //yeh bta rha h k yeh conten is page ka h

        <h3>content of add comment</h3>

    @endsection


NOTE:

    agr ap ny pre-existing migration mai koi changing krni h ya koi data add krna h to ap migration mai jao gy aur udher jo changing krni h kro k like

        ($table->string('comment'); ------>>>> $table->text('comment');)

    phr php artisan migrate kro gy to chaning to ho jae gi lkn is ki wja sy ap ka existing data delete ho jae ga to is chezz ko haal krny k liya 


    create kro ak migration 

    php artisan make: migration add_abc_to_posts(posts is table name)

    suppose post k table mai column add krna tha(add_abc_to_posts) is migration mai jao udher add kro colmun 

    $table->timestamp('status');

    us k bad ap ny dobara migration krni h

    php artisan migrate (in cmd)

    column will be created in posts table


ELOQUENT MODEL 

    model mai code add nhe dy gy Eloquent model only give access to communciate with database


SAVE DATA 

    controller.php


    $newPost = new Post;

    $newPost->title = "ALI RAZA";

    $newPost->gender = "Male";

    $newPost->save();


    or


    $newPost = Post::create([

        'title' => 'ALI RAZA' //$request['name']

        'gender' => 'Male' //$request['gender']

    ]);

    $newPost->save();


    or


    Post::create([

        'title' => 'ALI RAZA' //$request['name']

        'gender' => 'Male' //$request['gender']

    ]);


    $customer->id; get id after save


    Saving krty wqt let suppose ap ka data koi miss ho jaata h aur wo bd main ata to uss k liya hum fill funcrion use krian gy

    

    $customer = new Customer([

        ‘name’ => ‘Qasim’,

    ]);

    $customer->save();


    $customer fill([

        ‘address’ => ‘anything’,

        ‘phone’ => ‘anything’,

    ]);


    and in model to overcome MASS ASSIGNMENT error 

    Kbhi kbhi esa hta h k ap chahty ho k ap k input field mai koi value na edit ho sky like bagir permission k  koi admin na bn sky ( suppose ap ny status rkha h if value is 1 then person is admin if 0 then person normal user hacker status ko chnge na paie )uss k liya hum bnae gy 


    model.php

    Out side the function

    protected $guarded=[‘variables name which u don,t want to chnge’];

    

    OR

    Out side the function

    Protected $fillable=[‘variable which u want to fill’];

    Wo variable fill ho gy jo fiilable ai bnae hain bki nhe hongy

    Dono mai s yak use ho gi


    protected $fillable = ['title','gender'];

    

GET DATA

    Controller.php


    BOTH query fetch kry ga only one record;


    $post = Post::where('id','2')->first(); 


    or


    $post = Post::find('2');


    in dono mai difference yeh k find record sirf primary key k sth kam krta h aur where sub k sth krta h


UPDATE DATA

    Controller.php    


    $post = Post::find('2');

    $post->title = "ALI RAZA";

    $post->gender = "Male";

    $post->save();


    or


    $post = Post::findOrFail(2);

        'title' => 'ALI RAZA' //$request['name']

        'gender' => 'Male' //$request['gender']

    ];

    if found

    Post::where('id', '2')->update($input);


    View.php


    Normally insert to POST sy ho kata h lkn laravel update krty wqt put request krta h so edit page mia @csrf k bad @method('PATCH') likhna h

    and action main /{{$contact->id}}



DELETE DATA

    Controller.php     


    $post = Post::find('2');

    $post->delete();


    or 


    Post::destroy(2);


LARAVEL TINKER


    artisan command which is used to communicate with database

    (agr cmd mai database sy communication krna h to tinker use kry gy) 


    php artisan tinker

    PRESS ENTER

    $post = new \App\Post;

    $post->title = "ALI RAZA";

    $post->gender = "Male";

    $post->save(); 


LARAVEL VALIDATION


    SETTING VALIDATION

    $this->validate($request, [

        'name' => 'required|max:60'

    ]);

    

    OR


    $request->validate([

        'name'=>'required'

    ]);


    [if success than] 


    SHOW ERRORS IN VEIW


    @error('name')

        {{$message}}

    @enderror


LARAVEL SESSION

 

    GIVE SESSION TO VIEW (like flashmessage)


    redirect('page name')->with('msg','Some message');


    Check session (in view)


    if(Session::has('msg'))

    {

        Session::get('msg');

    }


CREATE SESSION

    Suppose ap ny session bnana h uss k liya apka code   

    aur new value put krny k liya b yeh hoga 

    

    session->put('msg', 'MY message');

    OR

    session(['msg'=>'My message']);


RETRIEVE SESSION

    session->get('msg', 'MY message');

    OR

    Session('msg');


FLASH SESSION

    flash message k liya hum yeh use krain gy

    session->flash('msg', 'MY message');


REFLASH SESSION

    suppose ap ny ak function mai flash bnya h aur uss k bad next function call hue h us k andr view pra h to flash mesage show krwany k liya (flash message ko ak sy zyda call tk rkhny k liya)


    public function flashSession()

    {

        session()->flash('msg', 'this is my flash message');

        return $this->recheck();

    }

    public function recheck()

    {

        session()->reflash();

        return view('check');

    }


MIDDLEWARE     

    middleware is hum http request py validation hti h like session check or http request kisi special are sy aa rha h 


    middleware on krny k liya 

    

    php artisan make:middleware CheckSession

    

    then kernal mai jao udr 3 types hti hain all http request, group request, single http request


    KERNAL.PHP 

    'checksession' => \App\Http\Middleware\CheckSession::class,


    WEB.PHP

    //Group middleware

    Route::group(['middleware' =>'checksession'], function(){

        Route::get('/about', function() {

            echo "I am in about page";

        });

        Route::get('/contact', function() {

            echo "I am in contact page";

        });

    });


    //Single middleware

    Route::get('singlecheck', function() {

        echo "I have session in me";

    })->middleware('checksession');


STUB CUSTOMIZATION

    Agr ap chahty ho k ap jo b code new chezz add kro ussmai phly sy e e kch code ho to ap stub use krty ho like(supposse ap chaty ho k ap k jb b new controller bny uss mai contructer phly e pra ho uss k liya stub use krty hain)


    php artisan stub:publish


ROUTE MODEL BINDING

    basically bagir query k url mai koi data pass kr k hum databasesy data get kr skty hain like url mai slash k bad id (product/3) or slash k bad product ka name (product/mobile)


    FOR ID

    

    Route::get('routemodel/{id}', 'customController@routeModel');

    public function routeModel(Comment $result)

    {

        return $result;

    }

    

    FOR EMAIL

    Route::get('routemodel/{result:email}', 'customController@routeModel'); 

    public function routeModel(Comment $result)

    {

        return $result;

    }  


    Basically Comment (is tabe ka name us mai url mai jis for mai b dain gy wesy data search ho ga jesa meny second code mai email search kiya h us ka name $result rekha h )


ACCESSORS     

    basically run time data sy koi data fecth krty e manuplate krny ko kehty hain (suppose ap data fetch kiya h us mai name field h ap us ka first letter capital krna chahty hain )


    MODEL.PHP(jiss table sy get kr rhy ho us ka model h)

    public function getFullnameAttribute($result)

    {

        return ucfirst($result);

    }

    yeh syntax as it is likhna h getFullnameAttribute 

    get(Fullname is column name)Attribute

    ucfirst is first letter capital


MUTATOR

    same like ACCESSORS h like hum data get kr k mrzi ki sting lga lyty thy aur data b efect nhe hta tha lkn is mai humain set krna hta h like save krty wqt Qasim Raza name ata h lkn hum chahty hain k save krny sy phely Mr automatic lg jae to us k liya mutator use krty hain


    public function setFullnameAttribute($value)

    {

        $this->attributes['fullname']= "MR".$value;

    }

FLUENT STRING

    

    Old way

    use Illuminate\Support\Str;

    $output = "hi my name is ali";

    $output = Str::urfirst($output);

    $output = Str::replace('Hi','hello'$output);

    $output = Str::camel($output);

    

    output will me 

    hello My name Is ali


    FLUENT STRING way

    $output = "hi my name is ali";

    $output = Str::of($output)

               ->urfirst($output)

               ->replace('Hi','hello'$output)

               ->camel($output);


    output will me 

    hello My name Is ali


SANCTUM

    What is Laravel Sanctum ? Laravel Sanctum provides a featherweight authentication system for SPAs (single page applications), mobile applications, and simple, token based APIs. Sanctum allows each user of your application to generate multiple API tokens for their account. These tokens may be granted abilities / scopes which specify which actions the tokens are allowed to perform..


    https://github.com/anil-sidhu/laravel-sanctum  


SEEDING

    let suppose ap ny database mai dumpy data send krna h bagir interface k to us ko krny k liya mai seedeer us krain gy    


    create seeder in cmd

    php artisan make:seeder CommentSeeder


    than go in created Seeder

    root>>database folder>>seedder folder

    CommentSeeder.php

    in run function


    jb hum new seeder bnaty hain aur seeder run krny sy phely 

    composer dump-autoload


    seeder ko run krny k liya

    php artisan db:seed --class CommentSeeder


    (if files missing than add in top of created seeder)

    use Illuminate\Support\Facades\DB;

    use Illuminate\Support\Facades\Hash;

    use Illuminate\Support\Str;


    (Note)MAKING MORE RECORDS ARE CALLED FACTORY


HELPERS

    wo function wo ap kahe b access kr skty hain 

    create a helper file anywhere you want (usually in app>helper folder)

    

    customHelper.php    

    <?php   

        if(!function_exists('random')) {

            function random() {

                return rand(10,1000);

            }

        }

    ?>

    

    go to the compser.json (in root)

    under autoload add the helper

    "files": [

        "app/Helper/customHelper.php"

    ]


    than dump the composer

    (in cmd)

    composer dump-autoload


    after that use any where you want 


Custom FACADE 

    yeh helper ki trha hty hain aur yeh puri class hti h 


    1- create a custom facade folder     

    2- create a file (class whome function are to be used)

    3- create service provider

    4- create class(whom function are be used) facade file

    5- register service provider(custom service provider) and alies(customfacades) in root>>confi folder>app.php

    6- that use any where you want


    create a custom facade folder 


    create a foler in app folder

    customFacades folder


    create a file

    Payment.php


    namespace App\CustomFacades;

    class Payment

    {    

        function paymentFunction() {

            echo "Payment function in function class";

        }

    }


    create class(whom function are be used) facade file

    in same folder (customFacde)

    PaymentFacades.php


    namespace App\CustomFacades;

    use Illuminate\Support\Facades\Facade;

    class PaymentFacades extends Facade {


        protected static function getFacadeAccessor() {

            return 'payment';

        }

    }


    create service provider

    php artisan make:provider PaymentServiceProvider


    you will find service provider in root>>app>>provider

    PaymentServiceProvider.php


    include your class in top

    use Illuminate\Support\ServiceProvider;

    public function register()

    {

        $this->app->bind('payment',function(){ //payment fist L in smal

            return new Payment();    //Payment is class name

        });

    }


    register service provider(custom service provider) and alies(customfacades) in root>>confi folder>app.php

    

    app.php

        add app service provider in providers

        App\Providers\PaymentServiceProvider::class,


        add customFacede in alias

        'Payment' => App\CustomFacades\PaymentFacades::class,


    how to user

        Payment::paymentFunction();    

        

    Expanation phely hum ny wo class bnae h jiss k function hum ny user krny hain phr us ko humny service provider mai kiya h jis mai humny usy bind kiya h payment class sy uss k bad humny csutomfacade bnya h jisny humari payment class ko facede class sy extend kiya h 

        

TOPIC TO DO          

    LOCALIZATION (make multi language)  

    mail

    payment method

    relation db

    make  foriein key in migration


ERRORS 

    IF GOT 419 error


    Solution

    In your form 

    <form method="POST" action="/profile">

    @csrf

    ...

    </form>


    In your head tag

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


    In Your Script tag

    $.ajaxSetup({

        headers: {

            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')

        }

    });


MAIL 

    

    What I like to do now when working locally is using something like Gmail to send mails, all you need to do is providing you personal - or custom dev email - credentials in .env file.


    As for online, you need to create an email - example@my-domain.com in your cpanel, and check your server configuration for mail port, driver and host:


    env file

    

    online

    MAIL_DRIVER=smtp

    MAIL_HOST=mail.my-domain.com

    MAIL_PORT=2525

    MAIL_USERNAME=example@my-domain.com

    MAIL_PASSWORD=secret  


    local

    MAIL_DRIVER = smtp

    MAIL_HOST = smtp.gmail.com

    MAIL_PORT = 587

    MAIL_USERNAME = your-gmail-username

    MAIL_PASSWORD = your-application-specific-password

    MAIL_ENCRYPTION = tls


    after that 

    php artisan config:cache


    craete controller


ONLY FOR READING

FORM CREATION


    1- composer.json mai ak dependency add krni h

    2- go to require section then add("laravelcollective/html":"^5.3.0"then go to cmd 

    Open to the project E:>cd xamp\htdocs\htdocs\laravel-project composer update

    3- go to config folder then app.php then go to provider (Illuminate\Html\HtmlServiceProvider::class)

    Then go to aliases array then add

    (     'Html' =>  Collective\Html\HtmlFacades::class,

            'Form' => Collective\Html\HtmlFacades::class,  )


    Illuminate HtmlServiceProvider is not supported to laravel 5.3 or about instated of Illuminate , You have to use Collective package as follows- terminal composer require "laravelcollective/html":"^5.2.0" Next, add your new provider to the providers array of config/app.php: 'providers' => [ Collective\Html\HtmlServiceProvider::class, ], Finally, add two class aliases to the aliases array of config/app.php: 'Form' => Collective\Html\FormFacade::class, 'Html' => Collective\Html\HtmlFacade::class,?

    Show less





    Creating view


    Web.php


     1 Route::get("/","FirstController@showdata");


     2 Route::Post('/formsubmit',

        [

            "uses" => "FirstController@submitData",

            "as" => "Formsubmit",

        ]);


    Contoller.php


    public function submitData(Request $request){

            $username =  $request->input('username');

            echo $username;    }


    View.php


    {!!Form::open(['route'=>'Formsubmit'])!!}

    {!!form::text('username')!!}

    {!!form::submit('submit')!!}

    {!!form::close()!!}


MAKE MULTI USER IN LARAVEL

    https://www.devopsschool.com/blog/how-to-create-multiple-role-based-authentication-and-access-control-in-laravel-application/


CRUD IN JQUERY

    https://makitweb.com/insert-update-and-delete-record-with-ajax-in-laravel/    


UNDERSTANDING OF AUTHENTICATION

    https://www.youtube.com/watch?v=3I1dCtvmBbk&list=PLe30vg_FG4OTO7KbQ6TByyY99AiSw1MDS&index=4&ab_channel=Bitfumes


Comments

Popular posts from this blog

Laravel 8 Multi Auth (Authentication) Tutorial

MySQL - Stored Procedures && Functions

crons job