Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel takes the pain out of development by easing common tasks used in many web projects, such as:
- Simple, fast routing engine.
- Powerful dependency injection container.
- Multiple back-ends for session and cache storage.
- Expressive, intuitive database ORM.
- Database agnostic schema migrations.
- Robust background job processing.
- Real-time event broadcasting.
Laravel is accessible, powerful, and provides tools required for large, robust applications.
Laravel has the most extensive and thorough documentation and video tutorial library of all modern web application frameworks, making it a breeze to get started with the framework.
If you don't feel like reading, Laracasts can help. Laracasts contains over 2000 video tutorials on a range of topics including Laravel, modern PHP, unit testing, and JavaScript. Boost your skills by digging into our comprehensive video library.
We would like to extend our thanks to the following sponsors for funding Laravel development. If you are interested in becoming a sponsor, please visit the Laravel Patreon page.
- Vehikl
- Tighten Co.
- Kirschbaum Development Group
- 64 Robots
- Cubet Techno Labs
- Cyber-Duck
- Many
- Webdock, Fast VPS Hosting
- DevSquad
- Curotec
- OP.GG
- WebReinvent
- Lendio
Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the Laravel documentation.
In order to ensure that the Laravel community is welcoming to all, please review and abide by the Code of Conduct.
If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell via taylor@laravel.com. All security vulnerabilities will be promptly addressed.
The Laravel framework is open-sourced software licensed under the MIT license.
#lista azioni
npm install
npm install bootstrap
npm install @popperjs/core
creata folder components con dentro layout.blade con inizializzazione doc html {{$slot}} e link per css e script {{asset('css/app.css')}}
in app CSS @import '~bootstrap/dist/css/bootstrap';
in app JS require('bootstrap');
lanciare o npm run dev o npm run watch per il building degli assets
creata view nav e navbar
inserito nel layout il componente
Per la creazione del database
winpty mysql -u root -p
create database simplycrud;
nel file .env impostare il database
DB_DATABASE=simplycrud DB_USERNAME=root DB_PASSWORD=root
Creare controller
php artisan make:controller PublicController
nel controller public function welcome(){ return view("welcome"); } }
nel web.php settare
Route::get('/', [PublicController::class, "welcome"] )->name("welcome");
importare la classe
andare nella vista welcome cancellare cosa c''è e inserire
INSTALLAZIONE FORTIFY PER AUTENTICAZIONE
composer require laravel/fortify
php artisan vendor:publish --provider="Laravel\Fortify\FortifyServiceProvider"
php artisan migrate
in config\app.php all'interno dei providers inserire App\Providers\FortifyServiceProvider::class,
in App\Providers\FortifyServiceProvider
inserire le viste richieste per il login e il register nella funzione di boot()
Fortify::loginView(function (){return view('auth.login');});
importare la classe FORTIFY se necessario
Fortify::registerView(function (){ return view('auth.register'); });
Creare folder nelle views auth e le viste login e register con il layout importato dentro
Modificare la navbar con le rotte che servono
@guest
inserire nelle viste di register e login il display di errori
@if ($errors->any())
-
@foreach ($errors->all() as $error)
- {{ $error }} @endforeach
inserire form nel register e nel login
gli attributi sono name="name" name="email" name="password" name="password_confirmation"
settare il form
PER IL REGISTER:
@csrfPER IL LOGIN @csrf
INSEIRE NELLA NAV UTENTE IN SESSIONE E TASTO LOGOUT CON JAVASCRIPT
Ricorda di inserire il tutto tra @else e la fine del @endguest per non far scattare errori
@else
@endguest
IN RouteServiceProvider
public const HOME = '/';
Creazione modello brewery
php artisan make:model Brewery -mcr
fa migrazione, controller e nel controller crea le funzione necessarie per il crud
SETTARE IL DATABASE
$table->id();
$table->string("name");
$table->string("address");
$table->text("description");
$table->string("owner");
$table->string("img");
$table->string("site")->nullable();
$table->timestamps();
Ora settare il modello
protected $fillable = [ 'name', 'address', 'description', 'owner', 'img', 'site', ];
lanciare migrazione
php artisan migrate
NEl controller brewery
public function create() { return view("brewery.create"); }
creare nelle viste la fold brewery e la vista create.blade.php
nella vista inserire x-layout
inserire un nuovo form
@csrf
<button type="submit" class="btn btn-primary">Register</button>
</form>
Settare le rotte per il form di creazione
Route::get("/brewery/create" , [BreweryController::class, "create"])->name("breweryCreate");
Route::post("/brewery/store", [BreweryController::class, "store"])->name("breweryStore");
nella nav nella vista autorizzata
nella funzione store del BreweryController inserire un dd per testare il funzionamento
public function store(Request $request) { dd($request -> all()); }
se funziona usare il mass assignment per creare istanze
public function store(Request $request) { // dd($request -> all());
Brewery::create([
'name' => $request->name,
'address' => $request->address,
'description' => $request->description,
'owner' => $request->owner,
'site' => $request->site,
'img' => $request->file('img')->store("public/img"),
]);
return redirect(route("breweryIndex"));
}
php artisan storage:link per collegare le immagini presenti nel public nella cartella storage
Settare ora funzione index nel modello brewery
public function index() { return view("brewery.index"); }
creare vista index.blade.php nella folder delle viste delle brewery e inserire l'x-layout dentro
creare la rotta per l'index delle breweries
Route::get("/brewery/index" , [BreweryController::class, "index"])->name("breweryIndex");
nella navbar fuori dal guest e auth
nella funzione index della brewery
public function index() { // $breweries = Brewery::all(); $breweries = Brewery::orderBy("created_at", "DESC")->paginate(2); return view("brewery.index", compact("breweries")); }
Nella vista dell'index
@foreach ($breweries as $brewery)
{{$breweries->links()}} questa è la paginazione di laravel
con la paginazione potrebbe visualizzarsi male l'icona della freccia perché di default laravel usa TailwindCSS ma ora noi in questo progetto stiamo usando bootstrap. Quindi in AppServiceProvider.php nella funzione di boot() public function boot() { Paginator::useBootstrap(); }
di questa classe per l'import use Illuminate\Pagination\Paginator;
creare rotta parametrica per il tasto detail
Route::get("/brewery/show/{brewery}", [BreweryController::class,"show"])->name("breweryShow");
Nel brewery controller
public function show(Brewery $brewery) { return view("brewery.show",compact("brewery")); }
creare la vista blade show.blade.php e inserire l'x-layout
rifare una card dentro con i valori e proprietà degli oggetti
Creare relazione tra birrerie e utenti che registrano
php artisan make:migration add_user_id_to_breweries
sostituire l'owner per associarlo all'utente registrato in sessione
NELLA MIGRAZIONE APPENA CREATA public function up() { Schema::table('breweries', function (Blueprint $table) { $table->dropColumn('owner'); $table->unsignedBigInteger('user_id')->after('description')->nullable(); //vincolo di integrità referenziale (la chiave esterna) $table->foreign('user_id')->references('id')->on('users'); }); }
public function down() { Schema::table('breweries', function (Blueprint $table) { $table->dropForeign(['user_id']); $table->dropColumn('user_id'); $table->string('owner')->after('description')->default('no_name'); }); }
NEL MODELLO USER SETTARE RELAZIONI
public function breweries(){ return $this->hasMany(Brewery::class); }
RICORDA DI IMPORTARE LA CLASSE BREWERY
SETTARE IL MODELLO BREWERY
public function user(){ return $this->belongsTo(User::class); }
Ora modificare la funzione di store per associare questi collegamenti
$brewery = Auth::user()->breweries()->create([ 'name' => $request->name, 'address' => $request->address, 'description' => $request->description, 'owner' => $request->owner, 'site' => $request->site, 'img' => $request->file('img')->store("public/img"), ]);
Ora creare il middleware per proteggere tutto il funzionamento
nel brewery controller
public function __construct(){ $this->middleware('auth')->except('index'); }
ora settarci la manytomany
e quindi creare le birre
php artisan make:model Beer -m
inserite deirettamente tramite seeder
Nel modello beer
protected $fillable = ['name'];
public function breweries(){
return $this->belongsToMany(Brewery::class);
}
NEL MODELLO BREWERY
Nella migrazione
public function up() { Schema::create('beers', function (Blueprint $table) { $table->id(); $table->string('name'); $table->timestamps(); }); }
public function beers(){ return $this->belongsToMany(Beer::class); }
RICORDA DI IMPORTARE LE CLASSI
NEL SEEDER
public function run() { $beers = ['arrugant', 'Peroni' , 'Nastro azzurro', 'dreher','Menabrea','Heiniken','Guinness']; foreach($beers as $beer){ DB::table('beers')->insert([ 'name'=> $beer, 'created_at' => Carbon::now(), 'updated_at' => Carbon::now(), ]); } }
IMPORTA SEMPRE LE CLASSI
FARE migrazione e popolazione seeder
php artisan migrate:rollback
php artisan migrate --seed
Verificare in mysql
ORA SETTARE LA TABELLA PIVOT TRA DUE RELAZIONI
NB: devono essere nome due tabelle al singolare e in ordine alfabetico
php artisan make:migration create_beer_brewery_table
nella migrazione
public function up() { Schema::create('beer_brewery', function (Blueprint $table) { $table->id(); $table->unsignedBigInteger('beer_id'); $table->foreign('beer_id')->references('id')->on('beers'); $table->unsignedBigInteger('brewery_id'); $table->foreign('brewery_id')->references('id')->on('breweries'); $table->timestamps(); }); }
lanciare la migrazione
php artisan migrate
AGGANCIIO DELLE BIRRE AL MODELLO
nella funzione creazione nel BREWERYCONTROLLER
public function create() { $beers = Beer::all(); return view("brewery.create", compact("beers")); }
inserire menù a tendina con le birre
nella vista create.blade.php
mettiamo l'id perché nella option passiamo l'id che poi andiamo a relazionare con l'attach ad agganciare questi modelli n-n
NElla funzione store del brewerycontroller
$brewery->beers()->attach($request->beers);
Mostrare birrerie inserite nella birrerie nella vista show.blade
-
@foreach ($brewery->beers as $beer)
- {{$beer->name}} @endforeach
aggiungere la funzione destroy nel brewery controller
public function destroy(Brewery $brewery) { $brewery->beers()->detach(); $brewery->user()->disassociate(); $brewery->delete(); return redirect(route("breweryIndex")); }
All'interno della vista show.blade.php
@csrf @method('delete') Delete
CREARE LA ROTTA
Route::delete('/brewery/destroy/{brewery}',[BreweryController::class,'destroy'])->name("breweryDestroy");
cancellare nella funzione store del brewery controller 'owner' => $request->owner,
sostituirlo con 'user_id' =>Auth::user()->id,
Nel modello Brewery sostituire il fillable owner con 'user_id'
PER l'edit creare rotte
Route::get("brewery/edit/{brewery}", [BreweryController::class, "edit"])->name("BreweryEdit"); Route::put("brewery/update/{brewery}", [BreweryController::class, "update"])->name("BreweryUpdate");
nella funzione edit
public function edit(Brewery $brewery) { $beers = Beer::all(); return view('brewery.edit', compact('brewery','beers')); }
creare la vista blade e il form
nella funzione update
public function update(Request $request, Brewery $brewery) { $brewery->update([ 'name'=> $request->name, 'address' => $request->address, 'img' => $request->file('img')->store("public/img"), 'description' => $request->description ]);
//inserisco solo le birre che non ho
$brewery->beers()->sync($request->beers);
return redirect(route('breweryIndex'))->with('message','modify succesfull');
}