Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Laravel Framework PHP

94 views

Published on

Corso Laravel Framework PHP, MVC, Blade Esempio CRUD

Published in: Software
  • DOWNLOAD THE BOOK INTO AVAILABLE FORMAT (New Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://urlzs.com/UABbn } ......................................................................................................................... Download Full EPUB Ebook here { https://urlzs.com/UABbn } ......................................................................................................................... Download Full doc Ebook here { https://urlzs.com/UABbn } ......................................................................................................................... Download PDF EBOOK here { https://urlzs.com/UABbn } ......................................................................................................................... Download EPUB Ebook here { https://urlzs.com/UABbn } ......................................................................................................................... Download doc Ebook here { https://urlzs.com/UABbn } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THE can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THE is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBOOK .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, CookBOOK, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, EBOOK, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THE Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THE the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THE Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Be the first to like this

Laravel Framework PHP

  1. 1. Laravel 7
  2. 2. Corso Laravel di B. Ferrari2 Laravel Laravel è un Framework PHP free e opensource, creato da Taylor Oftwell, ideato per applicazioni Web MVC basato su Symphony. Si interfaccia con database relazionali tramite ORM (Object Relational Mapper) e ha un sistema di routing estremamente flessibile e configurabile.
  3. 3. Corso Laravel di B. Ferrari3 MVC MVC è l’acronimo di Model View Controller, rappresenta l’architettura adottata dagli sviluppatori per lo sviluppo del software. Questo pattern separa l’applicazione in 3 parti, il model, la view e il controller. Il Model gestisce il comportamento di base e la gestione dei dati dell’applicazione. La View gestisce l’interfaccia grafica e renderizza i dati in una forma tale che questi vengano visualizzati correttamente. I Controller ricevono gli input dall’utente, mettono in comunicazione i model con le view.
  4. 4. Corso Laravel di B. Ferrari4 MVC
  5. 5. Corso Laravel di B. Ferrari5 ORM Object-relational mapping è una tecnica per convertire tipi usando un linguaggio orientato agli oggetti. Viene spesso usato con database relazionali per renderli compatibili con modelli ad oggetti. ES. SQL query SELECT * FROM Flights WHERE active = 1 ORDER BY name Es. Laravel ORM $flights = AppFlight::where('active', 1) ->orderBy('name') ->get();
  6. 6. Corso Laravel di B. Ferrari6 Composer Composer è uno strumenti per gestire dipendenze fra i componenti software PHP, detto Dependency management. Laravel utilizza Composer per gestire le proprie dipendenze. Prima di poter utilizzare Laravel è necessario essere sicuri di avere installato composer sulla propria macchina.
  7. 7. Corso Laravel di B. Ferrari7 1 Installare Laravel Su Windows 1. Installare XAMPP (https://www.apachefriends.org/) 2. Installare Composer (https://getcomposer.org/) 3. Riavviare 4. Installare laravel comando da dos: “composer global require laravel/installer” 5. Creazione progetto dalla cartella di root (htdocs) su windows C:xampphtdocs, es “laravel new FirstProject” dove FirstProject è il nome del nostro primo progetto 6. Lanciare progetto aprire nel browser http://localhost/FirstProject/public/
  8. 8. Corso Laravel di B. Ferrari8 2 Installare Laravel
  9. 9. Corso Laravel di B. Ferrari9 1- Debug con Visual Studio Code 1 – Scaricare e installare Visual Studio Code da https://code.visualstudio.com/ 2- Installare PHP debugging exension, per fare ciò dal menu principale scegliere View → Extension → PHP Debug (Felix Beker) 3 – Lanciare Apache da XMPP Control Panel 4 – Scaricare xdebug Aprire url localhost/dashboard/phpinfo.php da questa pagina capiamo che versione di php abbiamo installato, visitiamo il sito xdebug.org/download e scarichiamo la dll corrispondente (es.php_xdebug-2.9.5-7.4-vc15-x86_64.dll) 5 - Installare xdebug andiamo a copiare la dll scaricata prima nella directory delle estensioni di php (nel mio caso C:xamppphpext) 6 – Apriamo php.ini e aggiungiamo la configurazione per abilitare XDEBUG [XDEBUG] xdebug.remote_enable = 1 xdebug.remote_autostart = 1 zend_extension = C:xamppphpextphp_xdebug-2.9.5-7.4-vc15-x86_64.dll
  10. 10. Corso Laravel di B. Ferrari10 2- Debug con Visual Studio Code 7 – Verifica installazione: riavviamo il Apache e apriamo da browser localhost/dashboard/phpinfo.php dovremmo vedere l’estensione abilitata
  11. 11. Corso Laravel di B. Ferrari11 3- Debug con Visual Studio Code 8 – Configurazione Debug Apriamo un progetto PHP (es. apriamo una cartella C:xampp htdocstestdebug conentente file index.php ) da icona debug o ctrl+shift+ D e aggiungiamo configurazione per il debug cliccando su “create lunch.json file” e selezionare environment PHP
  12. 12. Corso Laravel di B. Ferrari12
  13. 13. Corso Laravel di B. Ferrari13 4- Debug con Visual Studio Code 9 – Avviare il debug premere tasto debug e Run listen for xDebug e aprire da broswer il progetto che stiamo usando (es. http://localhost/testdebug) ora impostando un breakpoint dovremmo osservare che all’apertura della pagina il debug inizi a funzionare
  14. 14. Corso Laravel di B. Ferrari14 Struttura dell’applicazione La struttura dell’applicazione è composta del cartelle e sotto cartelle incluse in un progetto. App è la cartella che contiene buona parte dei sorgenti dell’applicazione model e controller; - apphttpcontrollers dove sono presenti controllers; - appresources qui troviamo i file per gli assets html, views e le risorse l’internazionalizzazione; - routes qui troviamo i punti di accesso all’applicazione web - databasemigrations qui troviamo gli script di migrazione, ovvero, gli script che permettono di trasformare il database in nelle varie versioni necessarie per lo sviluppo dell’applicazione;
  15. 15. Corso Laravel di B. Ferrari15 Struttura dell’applicazione
  16. 16. Corso Laravel di B. Ferrari16 Blade Blade è un semplice e allo stesso potente mezzo che laravel ci mette a disposizione per risolvere il problema dei template in PHP. I template permetto di non ripetere e di riutilizzare parti di codice all’interno delle view. Le view blade terminano con estensione .blade.php e sono salvate tipicamente nella cartella resources/views
  17. 17. Corso Laravel di B. Ferrari17 1- Esempio view Posso creare una view come salvata come resources/views/greeting.blade.php <html> <body> <h1>Hello, {{ $name }}</h1> </body> </html>
  18. 18. Corso Laravel di B. Ferrari18 2- Esempio view Posso mostrare la view precedente da una route Route::get('/', function () { return view('greeting', ['name' => 'James']); }); Quello che accadrà è che verrà mostrata la pagina greeting e al posto di {{ $name }} verrà sostituito con James
  19. 19. Corso Laravel di B. Ferrari19 1 - Blade definizione layout I due benefici principali che blade apporta alle nostre applicazione sono l’eredità e le sezioni. Le view blade contengono HTML arricchito dalle direttive @section, @yeld, @exetends e @parent.
  20. 20. Corso Laravel di B. Ferrari20 Ereditarietà e override di campi In una view padre possono definire un titolo così: @yield('title', 'Default Title'); Questo vuoldire che se alla view sarà definito ‘title’ verrà mostrato ‘Default Title’. Nella view figlio possono impostare title @section('title','Custom Title')
  21. 21. Corso Laravel di B. Ferrari21 Ereditarietà e ovverride di sezioni html In una view padre possono definire una sezione html così: @section('some_div') <h1>Default Heading1</h1> <p>Default Paragraph <span>Default Span</span> </p> @show In una view figlia possono ridefinire una sezione html così: @section('some_div') @parent <h1>Custom Heading1</h1> <p>Custom Paragraph <span>Custom Span</span> </p> @endsection @parent mi permette di ripetere la sezione del padre nella view figlia
  22. 22. Corso Laravel di B. Ferrari22 Es. View padre <html> <head> <title>App Name - @yield('title')</title> </head> <body> @section('sidebar') This is the master sidebar. @show <div class="container"> @yield('content') </div> </body> </html> <!-- Salvato in resources/views/layouts/app.blade.php -->
  23. 23. Corso Laravel di B. Ferrari23 Es. View Figlio @extends('layouts.app') @section('title', 'Page Title') @section('sidebar') @parent <p>This is appended to the master sidebar.</p> @endsection @section('content') <p>This is my body content.</p> @endsection <!-- salvato in resources/views/child.blade.php -->
  24. 24. Corso Laravel di B. Ferrari24 1 - Laravel 7 CRUD MySQL 1) Installare Laravel composer create-project --prefer-dist laravel/laravel Blog 2) Creare database laravel e configurare credenziali database Aprire il file .env DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=il nome del tuo database (laravel) DB_USERNAME=il nome utente del tuo database (root) DB_PASSWORD=la password del tuo database
  25. 25. Corso Laravel di B. Ferrari25 2 - Laravel 7 CRUD MySQL 3) Generare Model e Migrazione Generiamo la tabella “product” e il suo migration file usando il seguente comando: php artisan make:model Product -m Questo comando permette di creare un model con nome Product e il migraton file per la tabella product con lla data corrente in database/migrations/ 2020_05_18_124707_create_products_table.php In questo file andiamo ad inserire il seguente codice che ci permette di creare una nuova tabella con campi id, title, product_code, description e i timestamp (created_at e updated_at).
  26. 26. Corso Laravel di B. Ferrari26 3 - Laravel 7 CRUD MySQL <?php useIl lumi nateSupportFacadesSchema; useIl lumi nateDatabase SchemaBlueprint; useIl lumi nateDatabase MigrationsMigrati on; class Creat eProductsTable extendsM igrat ion { /* * * Run themigr ations. * * @return void * / public function up() { Schema::create('product s', function(Bluepr int $table) { $table->increments('id'); $table->string('titl e'); $table->string('product_code') ; $table->text( 'descri ption'); $table->timestamps(); }); } /* * * Reverset hemigrations. * * @return void * / public function down() { Schema::dropIfExists('products'); } } Next, migr ate thet able using thebelow command. phpar tisan mi grate I f you foundanyquerybuilder error incommand prompt go to =>appProvider sAppServiceProvider. php andput thebelow codehere: useI lluminateSupport FacadesSchema; publi cfunction boot () { Schema::defaul tStri ngLength(191); } Andthenrunthisbelow command: phpartisanmi grate:fresh Now, addthefi llabl eproperty insideProduct .php file. <?php namespaceApp; useI lluminateDatabaseEloquentM odel ; class Product extendsM odel { protected$fill able =[ 't itle', 'product_code', 'descri ption', ]; } 4). Cr eate Resource Route &Controll er Create the ProductControl ler usingt hebelow command. phpar tisan make:control ler Pr oduct Contr oller -- resource Thiscommand will createacontol ler name ProductControll er andalsoinside bydefault seven met hods like index, store, create, update, dest roy, show, edit. Next, Weneed toaddthe resourcer oute. Go tor outes/web. phpput thebelow routeshere : <?php Route::get ('/', f uncti on( ) { r eturn view ('w elcome'); }); Route: :resource('products', 'ProductControll er'); Next opencontr oller , Go toapp/HTTP/Control ler/ProductContr oller and put thebelow code here : ? 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 <?php namespaceAppHttpControllers; useAppProduct; useIl lumi nateHttpRequest; useRedirect; usePDF; class ProductControl ler extends Cont roller { /* * * Displaya listing of the resource. * * @return Ill uminateHt tpResponse * / public function index() { $data['products'] = Product::orderBy('id','desc')->paginate(10); ret urn view ('product.li st',$data); } /* * * Show the for mfor creating anew resource. * * @return Ill uminateHt tpResponse * / public function creat e() { ret urn view ('product.cr eate') ; } /* * * Stor eanewl ycreatedr esour cein stor age. * * @param Il lumi nateHttpRequest $r equest * @return Ill uminateHt tpResponse * / public function store(Request $r equest) { $request->validat e([ 'tit le'=> 'required', 'product_code' =>'required', 'descript ion'=>'required', ]); Product ::create($request->al l()); ret urn Redir ect:: to('products') ->w ith( 'success','G reate! Product creat edsuccessfully. '); } /* * * Displayt hespecif iedresource. * * @param AppProduct $product * @return Ill uminateHt tpResponse * / public function show (Request $r equest) { } /* * * Show the for mfor edit ingt hespecifi edr esour ce. * * @param AppProduct $product * @return Ill uminateHt tpResponse * / public function edit( $id) { $w here =ar ray('i d'=>$id); $data['product_inf o'] =Product::w here($where)- >first (); ret urn view ('product.edit', $data) ; } /* * * Updatethespecifi edresource instorage. * * @param Il lumi nateHttpRequest $r equest * @param AppProduct $product * @return Ill uminateHt tpResponse * / public function updat e(Request $request, $id) { $request->validat e([ 'tit le'=> 'required', 'product_code' =>'required', 'descript ion'=>'required', ]); $update =['t itle' =>$request ->tit le, 'descr iption'=>$request->descr iption]; Product ::where('i d',$id) ->update($update); ret urn Redir ect:: to('products') ->w ith( 'success','G reat! Product updatedsuccessf ully'); } /* * * Removet hespecif iedresourcefromst orage. * * @param AppProduct $product * @return Ill uminateHt tpResponse * / public function destr oy($id) { Product ::where('i d',$id) ->del ete() ; ret urn Redir ect:: to('products')->w ith( 'success','Pr oduct delet edsuccessfull y'); } } 5). Cr eate the blade view Weneedto createsome blade view sfil es, Got oapp/resources/ view s/ andcr eate onefolder name product. Insi dethe product f older createt hefol lowi ngbl ade files. Create the product f older .After successfully creat eproduct f older than create4 foll owing bladefil es. Layout .blade.php List.blade. php Create.blade.php Edit.blade. php Layout .blade.php ? 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 <!DOCTYPE html> <html > <head> <meta char set=" UTF-8"> <meta name="vi ewport" content ="wi dth=device-wi dth, i nitial-scale=1.0"> <meta http-equi v="X- UA-Compati ble" cont ent=" ie=edge"> <meta name="csrf-token" content="{{ csr f_token() }}"> <t itle>Laravel CRUDTutorial Wi thExample- Tutsmake.com</ title> <l inkhref="//maxcdn.bootstrapcdn.com/bootst rap/4.1.1/css/bootstr ap.min.css" r el="st ylesheet" id=" bootstrap- css"> <style> body{ background- color : #25274d; } .contai ner{ background: #ff9b00; padding: 4%; border- top- left- radius: 0.5rem; border- bott om-l eft-r adius: 0.5r em; } </ style> </head> <body> <divcl ass="cont ainer "> <br><br><br > @yield('content ') </ div> </body> </html> List.blade. php ? 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 @extends('product.layout') @sect ion('content') <ahref=" {{ route('pr oducts.cr eate') }}" class="btn btn- successmb-2">Add</a> <br> <di vcl ass=" row" > <di vcl ass=" col-12"> <table class="t ablet able- bordered" i d="l aravel_crud"> <thead> <tr > <th>Id</ th> <th>Titl e</th> <th>Product Code</t h> <th>Description</th> <th>Createdat </th> <td colspan="2">Act ion</ td> </t r> </thead> <tbody> @f oreach($productsas $product) <tr > <td>{{ $product->id }}</ td> <td>{{ $product->ti tle} }</t d> <td>{{ $product->pr oduct _code}}</td> <td>{{ $product->description }}</ td> <td>{{ date('Y- m-d', strt otime($product->created_at)) }}</ td> <td><ahref="{ { route('pr oducts.edit',$product ->id) }}" class="btn btn- primary">Edit</ a></ td> <td> <formaction="{{ r oute( 'products. destr oy', $product->id)}}" met hod=" post"> {{ csrf _field() }} @method('DELETE') <button class="btn btn- danger" type=" submi t">Delete</butt on> </form> </td> </t r> @endforeach </tbody> </table> { !! $pr oducts->links( ) !!} </div> </div> @endsecti on Create.blade.php ? 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 @extends('product.layout') @sect ion('content') <h2st yle=" mar gin-t op: 12px;" class="text-center" >Add Product</a></h2> <br> <form acti on=" {{ route('product s.store') } }" method="PO ST" name="add_product"> { { csr f_field() }} <divclass="row "> <divcl ass="col- md-12"> <di vcl ass=" form-group"> <st rong>Title</strong> <input t ype=" text" name="ti tle" class="for m-control" placehol der=" Enter Title"> <spancl ass=" text-danger ">{{ $err ors->first ('title') }}</span> </div> </ div> <divcl ass="col- md-12"> <di vcl ass=" form-group"> <st rong>Product Code</st rong> <input t ype=" text" name="pr oduct _code" class="form-contr ol" placeholder ="Enter Product Code"> <spancl ass=" text-danger ">{{ $err ors->first ('product_code') }}</span> </div> </ div> <divcl ass="col- md-12"> <di vcl ass=" form-group"> <st rong>Descr iption</str ong> <textareaclass="form-contr ol" col="4" name="description" placehol der=" Enter Descr ipti on"></text area> <spancl ass=" text-danger ">{{ $err ors->first ('descr iption') } }</span> </div> </ div> <divcl ass="col- md-12"> <button type="submit" class="btn btn-primary" >Submit</button> </ div> </div> </form> @endsection Edit.blade. php ? 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 @extends('product.layout') @sect ion('content') <h2st yle=" mar gin-t op: 12px;" class="text-center" >Edit Product</a></h2> <br> <form acti on=" {{ route('product s.update', $product_info- >id) } }" method="PO ST" name="update_pr oduct "> { { csr f_field() }} @met hod('PATCH') <divclass="row "> <divcl ass="col- md-12"> <di vcl ass=" form-group"> <st rong>Title</strong> <input t ype=" text" name="ti tle" class="for m-control" placehol der=" Enter Title" val ue=" {{ $product_inf o->tit le}} "> <spancl ass=" text-danger ">{{ $err ors->first ('title') }}</span> </div> </ div> <divcl ass="col- md-12"> <di vcl ass=" form-group"> <st rong>Product Code</st rong> <input t ype=" text" name="pr oduct _code" class="form-contr ol" placeholder ="Enter Product Code" val ue="{ { $product_info->product_code }}"> <spancl ass=" text-danger ">{{ $err ors->first ('product_code') }}</span> </div> </ div> <divcl ass="col- md-12"> <di vcl ass=" form-group"> <st rong>Descr iption</str ong> <textareaclass="form-contr ol" col="4" name="description" placehol der=" Enter Descr ipti on" >{{ $product_info->description }}</t extar ea> <spancl ass=" text-danger ">{{ $err ors->first ('descr iption') } }</span> </div> </ div> <divcl ass="col- md-12"> <button type="submit" class="btn btn-primary" >Submit</button> </ div> </div> </form> @endsection 6). RunDevelopment Server I nthi sstep, w ew ill usethe PHP artisanserve command. It w ill start your server locally phpar tisan ser ve I f you want to run theproject diff rent port sousethisbel ow command phpar tisan ser ve-- port=8080 Now w ear ereadyt orun our exampleso run bell ow commandto quickrun. http:/ /localhost:8000/products Conclusion I nthi sart icle, We have successful lycr eatedlar avel CRUDApplication (Create, Read, Updat e, Delete) wi thexampl e. Our examplesrunqui ckly. Youmayli ke Laravel Tut orial FromScratch | StepBy Step LaravelAjax CRUD(Dat aTabl esJs) Tutorial Example Upload Files/Images toAmazon s3Cl oudUsing Laravel Filesystem LaravelAjax CRUD(O perat ion)Application Example LaravelAngular JSCRUDExample Tutorial AjaxI mage Upl oadI nLar avel Tutori al ExampleFr omScratch Laravel CKEditor wi thImageUpload Laravel Int ervention UploadImageUsingAjax –Example Upload Imaget oDat abase with Vali dationin laravel LiveDemo I f you have any questions or thought sto shar e, usethe comment form bel ow t oreachus. Categories: Lar avel, PHP Tagged Wit h: Laravel CreateUpdate Delet eExampl e, Laravel Crud Project With MySQ LDat abase Post navigation PREVIO US Previouspost:Laravel 7/6AutocompleteSearch wit hJqueryUI NEXT Next post:Laravel 7/ 6Email Verification Tut orial Example 2 repl iest oLaravel 7/6 Basic First CRUD Example Tutorial M ike 6 monthsago dowe have agithub repo for t hisapplication Reply AwaNdiaye Sene 4 monthsago t hanks you for all ! !! Reply Leave aReply Your email address will not bepublished. Requir edfi eldsaremarked * Comment Name * Email * Websi te PrimarySi debar Search for: Search SEARCH All BankIFSCCode Recent Post s JavaScriptArray Some JavaScriptArray map | It erateArray Element JavaScriptArray Reduce| ReduceArray toSingl eVal ue JavaScriptArray filt er| Filteri ngIt ems FromArray JavaScriptArray indexOf &last IndexOf: Find Element Positi oninArray Categories Angular Best FreeSEO Tools Boostr ap Codeigniter Composer G it ( Github) Javascript Jquery Laravel M ySQ L Nodej s PHP Python SEO Technology Ubuntu Windows Wordpress Recent Comments braj onCodeigniter 4RemovePublic and Index.php From URL M angal Sol anki onG et Latitudeand LongitudeFromaddress GoogleG eocodeAPI jQuery/javascr ipt Eugene onLaravel – Creat eCust omHelper Wi thExampl e w 3ant z on GoogleRecapt chav3 DemoExampl ePHP TutsM ake onLaravel PHP SimpleQ r CodesG ener ate Rushan onLaravel PHPSimpleQ r CodesG enerate M een onLaravel 7/6 Tutorial From Scrat ch| Step ByStep mahmoudonG et Country, City, lat itude, longitudefr omIP addr essusing PHP santhoshon Upl oadProject/FilesOn Git hub Using Command line yasher onLaravel 7/ 6Multiple Database ConnectionsWithSi ngle Project Tags 8 SimpleFree SeoTools toInstantl yImproveYour MarketingTodayBest FreeSeoToolsCr eate RESTApi using Laravel Passport Form Validat ionUsingAj axandJquery inLaravel 6FreeRs Chat PluginusingNodejs GoogleSeoChecker How -to-Install Laravel onWindow swi thComposer How t oImport Export Excel in Laravel How to Inst allApache inUbuntu 18.04 How toI nstall Laravel onw indow s10 How to Install Nodejs andNpm inWindow sHow to Install NodeJsin WindowsHow t oInstall Npm InWindow s10 How to Laravel ImageUpload in DatabaseHow to MakeUser LoginandRegistration Laravel How t oSendMai l in Laravel I nstal l NodejsandNPM in Wi ndow sInstall PHPin Ubuntuf rom Scrat chLar avel 5SendEmail ExampleLaravel CreateUpdate DeleteExample Laravel Crud Project Wi thM ySQL Dat abase Laravel FormValidation BeforeSubmit ExampleLaravel Import Excel toDatabaseLaravel Import Export Excel to Database ExampleLaravel Installation Processon Windows Syst emLaravel Logi nAuthenti cationUsi ngEmail Tutori al Laravel Mail Sendwi thExamplelaravel One toM anyRelat ionshipw ithExampl eLar avel Passport Laravel PHPAjax Form Submit Without Refresh PageLar avel SendEmail wit hExampl eLar avel t utori al Laravel Upl oadI mage UsingAjax Tutorial Laravel whereNotIn|w her eNotNull|w hereNotBet ween Mail Sendin Laravel w ithExampleNode.j schat NodejsNodej sChat PluginNodejs Chat Soket.io SendingEmail ViaG mail SM TPServer InLaravel SendMail PHPLaravel ExampleStepbyStepGui deto Buil ding Your First LaravelApplication Stri pePayement GatewayIntegration inLar avel UploadM ultipleImages inLaravel Woorank Seo Tools Footer Widgets Footer Menu Home About Us Contact Us PrivacyPol icy G uest Post Sitemap All BankIFSCCode RSChat Copyri ght © Tut sMake2020.All rightsreserved. xx <?php use IlluminateSupportFacadesSchema; use IlluminateDatabaseSchemaBlueprint; use IlluminateDatabaseMigrationsMigration; class CreateProductsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('products', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->string('product_code'); $table->text('description'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('products'); } }
  27. 27. Corso Laravel di B. Ferrari27 4 - Laravel 7 CRUD MySQL 4 – Migrare ora per ottenere la creazione della tabella eseguiamo la migrazione, con il seguente comando: php artisan migrate Questo ci permette di aggiornare il database all’ultima versione, eseguendo un’operazione di migrazione ovvero una trasformazione da una struttura del database a un’altra
  28. 28. Corso Laravel di B. Ferrari28 5 - Laravel 7 CRUD MySQL 5- Fillable property questo ci permette di determinare i campi modificabili nella nostra tabella durante le operazioni di crud, quindi aggiungiamo il seguente codice nel Model Product file app/product.php <?php namespace App; use IlluminateDatabaseEloquentModel; class Product extends Model { protected $fillable = [ 'title', 'product_code', 'description', ]; }
  29. 29. Corso Laravel di B. Ferrari29 6 - Laravel 7 CRUD MySQL 6 – Resoruce route e Controller questo operazione ci permette di creare il controller ProductController e al suo interno i 7 metodi creati di default index, store, create, update, destroy show e edit php artisan make:controller ProductController --resource Dopo questo comando eseguiamo una risorsa nel file di route, quindi andiamo nel file routes/web.php e inseriamo il codice seguente.
  30. 30. Corso Laravel di B. Ferrari30 Metodi controller HTTP Verb Path (URL) Action (Method) Route Name GET /product index product.index GET /product/create create product.create POST /product store product.store GET /product/{id} show product.show GET /product/{id}/edit edit product.edit PUT/PATCH /product/{id} update product.update DELETE /product/{id} destroy product.destroy
  31. 31. Corso Laravel di B. Ferrari31 7 - Laravel 7 CRUD MySQL <?php Route::get('/', function () { return view('welcome'); }); Route::resource('products', 'ProductController');
  32. 32. Corso Laravel di B. Ferrari32 8 - Laravel 7 CRUD MySQL 8 – Implementazione del Controller: Abbiamo ottenuto il controller con i vari metodi CRUD dichiarati ma non implementati, quindi ora ci serve implementare il metodi del controller Apriamo il file del controller app/HTTP/Controller/ProductController e andiamo a riempire i metodi generato con il codice seguente.
  33. 33. Corso Laravel di B. Ferrari33 9 - Laravel 7 CRUD MySQL namespace AppHttpControllers; use AppProduct; use IlluminateHttpRequest; use Redirect; use PDF; class ProductController extends Controller { public function index() { $data['products'] = Product::orderBy('id','desc')->get(); return view('product.list',$data); }
  34. 34. Corso Laravel di B. Ferrari34 10 - Laravel 7 CRUD MySQL public function create() { return view('product.create'); } public function store(Request $request) { $request->validate([ 'title' => 'required', 'product_code' => 'required', 'description' => 'required', ]); Product::create($request->all()); return Redirect::to('products') ->with('success','Greate! Product created successfully.'); }
  35. 35. Corso Laravel di B. Ferrari35 10.1 - Laravel 7 CRUD MySQL Action Create si preoccupa di mostrare la view product.create tramite l’istruzione return view('product.create'); Action Store prende in ingresso un oggetto di tipo Request che contiene i dati provenienti dalla form presente nella view product.create. Questi dati vengono validati tramite metodo validate, se la validazione fallisce verrà mostrata la view.create con un oggetto $errors contente gli errori generati dalla validazione. Se la validazione va a buon fine viene eseguito il metodo create del model Product e ad esso vengono passati i dati per eseguire la query di insert a database
  36. 36. Corso Laravel di B. Ferrari36 11 - Laravel 7 CRUD MySQL public function edit($id) { $where = array('id' => $id); $data['product_info'] = Product::where($where)->first(); return view('product.edit', $data); }
  37. 37. Corso Laravel di B. Ferrari37 11 - Laravel 7 CRUD MySQL public function update(Request $request, $id) { $request->validate([ 'title' => 'required', 'product_code' => 'required', 'description' => 'required', ]); $update = ['title' => $request->title, 'description' => $request->description]; Product::where('id',$id)->update($update); return Redirect::to('products') ->with('success','Great! Product updated successfully'); } public function destroy($id) { Product::where('id',$id)->delete(); return Redirect::to('products')->with('success','Product deleted successfully'); } }
  38. 38. Corso Laravel di B. Ferrari38 11.1 - Laravel 7 CRUD MySQL Action Edit mostra recupera i dati del prodotto attraverso il suo id, li passa alla view product.edit Action Update riceve i dati del prodotto dalla view product.edit esegue la validazione e se questa va buon fine esegue l’aggiornamento dei dati a database tramite istruzione Product::where('id',$id)->update($update);
  39. 39. Corso Laravel di B. Ferrari39 12 - Laravel 7 CRUD MySQL 9 – Implementazione delle view: a questo punto andremo a comporre le views. Andiamo a creare una cartella product all’interno della cartella app/resources/views/. Creiamo 4 files - Layout.blade.php che andrà a contenere il layout principale dell’applicazione - List.blade.php la view che conterrà la lista dei prodotti - Create.blade.php che conterrà la view per la creazione di un prodotto - Edit.blate.php che conterrà il modulo per editare un prodotto
  40. 40. Corso Laravel di B. Ferrari40 Layout.blade.php <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta name="csrf-token" content="{{ csrf_token() }}"> <title>Laravel CRUD </title> <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <style> body{ background-color: #25274d; } .container{ background: #ff9b00; padding: 4%; border-top-left-radius: 0.5rem; border-bottom-left-radius: 0.5rem; } </style> </head> <body> <div class="container"> <br><br><br> @yield('content') </div> </body> </html>
  41. 41. Corso Laravel di B. Ferrari41 List.blade.php @extends('product.layout') @section('content') @if (Session::has('success')) <div class="alert alert-success"> <ul> <li>{!! Session::get('success') !!}</li> </ul> </div> @endif <a href="{{ route('products.create') }}" class="btn btn-success mb-2">Add</a> <br> <div class="row"> <div class="col-12"> <table class="table table-bordered" id="laravel_crud"> <thead> <tr> <th>Id</th> <th>Title</th> <th>Product Code</th> <th>Description</th> <th>Created at</th> <td colspan="2">Action</td> </tr> </thead> <tbody> @foreach($products as $product) <tr> <td>{{ $product->id }}</td> <td>{{ $product->title }}</td> <td>{{ $product->product_code }}</td> <td>{{ $product->description }}</td> <td>{{ date('Y-m-d', strtotime($product->created_at)) }}</td> <td><a href="{{ route('products.edit',$product->id)}}" class="btn btn-primary">Edit</a></td> <td> <form action="{{ route('products.destroy', $product->id)}}" method="post"> {{ csrf_field() }} @method('DELETE') <button class="btn btn-danger" type="submit">Delete</button> </form> </td> </tr> @endforeach </tbody> </table> </div> </div> @endsection
  42. 42. Corso Laravel di B. Ferrari42 Create.blade.php @extends('product.layout') @section('content') <h2 style="margin-top: 12px;" class="text-center">Add Product</a></h2> <br> <form action="{{ route('products.store') }}" method="POST" name="add_product"> {{ csrf_field() }} <div class="row"> <div class="col-md-12"> <div class="form-group"> <strong>Title</strong> <input type="text" name="title" class="form-control" placeholder="Enter Title" value=”{{old('title')}”> <span class="text-danger">{{ $errors->first('title') }}</span> </div> </div> <div class="col-md-12"> <div class="form-group"> <strong>Product Code</strong> <input type="text" name="product_code" class="form-control" placeholder="Enter Product Code" value=”{{old('product_code')}”> <span class="text-danger">{{ $errors->first('product_code') }}</span> </div> </div> <div class="col-md-12"> <div class="form-group"> <strong>Description</strong> <textarea class="form-control" col="4" name="description" placeholder="Enter Description">{{old('description')}</textarea> <span class="text-danger">{{ $errors->first('description') }}</span> </div> </div> <div class="col-md-12"> <button type="submit" class="btn btn-primary">Submit</button> </div> </div> </form> @endsection
  43. 43. Corso Laravel di B. Ferrari43 Edit.blade.php @extends('product.layout') @section('content') <h2 style="margin-top: 12px;" class="text-center">Edit Product</a></h2> <br> <form action="{{ route('products.update', $product_info->id) }}" method="POST" name="update_product"> {{ csrf_field() }} @method('PATCH') <div class="row"> <div class="col-md-12"> <div class="form-group"> <strong>Title</strong> <input type="text" name="title" class="form-control" placeholder="Enter Title" value="{{ old('title') == '' ? $product_info->title : old('title')}}"> <span class="text-danger">{{ $errors->first('title') }}</span> </div> </div> <div class="col-md-12"> <div class="form-group"> <strong>Product Code</strong> <input type="text" name="product_code" class="form-control" placeholder="Enter Product Code" value="{{old('product_code') == '' ? $product_info->product_code : old('product_code') }}"> <span class="text-danger">{{ $errors->first('product_code') }}</span> </div> </div> <div class="col-md-12"> <div class="form-group"> <strong>Description</strong> <textarea class="form-control" col="4" name="description" placeholder="Enter Description" >{{ old('description') == '' ? $product_info->description : old('description') }}</textarea> <span class="text-danger">{{ $errors->first('description') }}</span> </div> </div> <div class="col-md-12"> <button type="submit" class="btn btn-primary">Submit</button> </div> </div> </form>
  44. 44. Corso Laravel di B. Ferrari44 13 - Laravel 7 CRUD MySQL 10 – Lancio dell’applicativo a questo punto possiamo lanciare l’applicativo usando il comando php artisan serve --port=8080 E visualizzare il risultato nel browser all’indirizzo http://localhost:8080/products
  45. 45. Corso Laravel di B. Ferrari45 Esercizio Aggiunger per ogni riga delle tabella un pulsante che mostra attraverso il metodo show tutti i dati della riga selezionata

×