getting_started_with_laravel

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
getting_started_with_laravel [20.11.2020 16:44] – [saving JSON in a MySQL table] Pascal Sutergetting_started_with_laravel [04.12.2020 11:44] (current) – [Basics] Pascal Suter
Line 8: Line 8:
 as with most successful programming languages and frameworks, Laravel seems to provide a good documentation. just go to the [[https://laravel.com|Laravel webpage]] and click on documentation.. the documentation link contains the version number, hence i won't hard link it here as it seems this would be obsolete in a few months anyway :)  as with most successful programming languages and frameworks, Laravel seems to provide a good documentation. just go to the [[https://laravel.com|Laravel webpage]] and click on documentation.. the documentation link contains the version number, hence i won't hard link it here as it seems this would be obsolete in a few months anyway :) 
  
-====== Laravel installation (on Ubuntu 20.04 with Apache2) ======+===== Laravel installation (on Ubuntu 20.04 with Apache2) =====
 I don't care or like the included web-server in laravel for development.. it isn't that much work to set up a proper webserver like you would have on your productive environment, so why not develop with a close to production environment as possible, so you can fix issues beforehand?  I don't care or like the included web-server in laravel for development.. it isn't that much work to set up a proper webserver like you would have on your productive environment, so why not develop with a close to production environment as possible, so you can fix issues beforehand? 
  
Line 77: Line 77:
  
  
-====== Basics ======+===== Basics =====
 Laravel follows the Model View Controller design principle.. where the View is basically your GUI, the Webpage in this case, the Model handles storing and reading your data.. so that's your database and some PHP scripts to access the database and retrieve Entries from it, and the Controller is the glue between the two, that's where your actual program logic happens.. the controller does something with the data and passes the result to the View.  Laravel follows the Model View Controller design principle.. where the View is basically your GUI, the Webpage in this case, the Model handles storing and reading your data.. so that's your database and some PHP scripts to access the database and retrieve Entries from it, and the Controller is the glue between the two, that's where your actual program logic happens.. the controller does something with the data and passes the result to the View. 
  
Line 103: Line 103:
  
 **processing delete requests** are like posts, but we can't set the form method to ''DELETE'' so we need to use a blade function ''@method('DELETE')'' just after the form tag.  **processing delete requests** are like posts, but we can't set the form method to ''DELETE'' so we need to use a blade function ''@method('DELETE')'' just after the form tag. 
-====== Naming Conventions ======+ 
 +**sessions and flashing data** in laravel we can either store data into our session, like in normal php.. we can do this either via the ''session()'' helper which will save new key=>value pairs when it is passed an array as argument like ''session(['newkey',$someVar])'' for example. to get ''$someVar'' back we would use the helper like ''$someVar=session('newkey')''. alternatively, we can use an instance of the ''Request'' class and the ''put()'' and ''get()'' functions for the ''session'' property like so: ''$request->session()->put('tmpfiles',$tmpfiles);'' and vice versa ''$tmpfiles = $request->session()->get('tmpfiles',[]);'' notice a nice feature of the ''get()'' method: we can pass a default value as a second argument which will be returned in case the session variable is not set. that's pretty helpful. Session variables are also available in blades by using the ''session()'' helper like above. <br> 
 +a specialty in laravel is, that we can **flash** data to a session. flashing means, that the data will only remain in the session for the next request. after that it will either be unset or we need to **reflash** to keep the flashed variables. to flash a variable to a session, we do the same as above with the ''get()'' function but now use a ''flash()'' method, that's it.  
 +===== Relations ===== 
 +relations are defined in the Model by adding a new public function to it.  
 + 
 +of course the migration must also contain the necessary fields to build the relations. the convention is to use something like  
 +<code php> 
 +$table->foreignId('job_id')->constrained(); 
 +</code> 
 +which will automatically define a foreing ID in the current table that is linked to the ''jobs'' (plural) table's ''id'' field. the ''constrained()'' method at the end is there to tell laravel to create a constraint in MySQL for this relationship.  
 + 
 +so here is how various relationships are defined in the model for the respective table(s) 
 +==== 1:1 relationships ==== 
 +here's an example.. the ''assessments'' table contains a field ''job_id'' defined like above, which links to a single job out of the ''jobs'' table:  
 + 
 +in the **Assessment Model** we write:  
 +<code php> 
 +public function job(){ 
 +    return $this->belongsTo('App\Models\Job'); 
 +
 +</code> 
 +and vice versa, in the **Job Model** we write:  
 +<code php> 
 +public function assessment(){ 
 +    return $this->hasOne('App\Models\Job'); 
 +
 +</code> 
 +now we can simply access the job via the assessment by using something like ''$assessment->job->name'' and vice versa we can get a property from the assessment via the job like so ''$job->assessment->overview'' 
 + 
 + 
 +===== Naming Conventions =====
 I'm going to use the examples of the above mentioned YouTube Series here, which is all about a pizza place :)  I'm going to use the examples of the above mentioned YouTube Series here, which is all about a pizza place :) 
   * Model Name: Pizza   * Model Name: Pizza
Line 120: Line 151:
  
  
-====== Tricks ====== +===== Form validation ===== 
-===== Create Model + Controller + Migration all in one step =====+Laravel provides a nice Method for validating forms. Typically the validator is added in the Controller ''store()'' method. here is an example:  
 +<code php> 
 +    public function store(Request $request){ 
 +        $validData $request->validate([ 
 +            'name' => ['required', 'string', 'max:255'], 
 +            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'], 
 +            'password' => ['required', 'string', 'min:8', 'confirmed'], 
 +        ]); 
 +        // anything from here on will only be executed if the above validation was successful 
 +     } 
 +</code> 
 +there are many [[https://laravel.com/docs/8.x/validation#available-validation-rules|validation rules]] available already in Laravel and custom rules can be added if needed.  
 + 
 +also note, that the ''$validData'' variable now contains an array with the validated data in a format that is compatible with the ''create'' methods for the laravel models. So if you set up your model's ''$fillable'' property correctly and your form field names correspond to your database field names, you can pass this array straight to the ''create()'' method of your model and create a new database entry like that! 
 + 
 +now here are a few cool things about the validator:  
 +  * if it finds an invalid field, it will stop right there and laravel will show you the form page again without any further routes needed.  
 +  * in addition to bringing the user back to the form, laravel will provide an ''$error'' variable which can be used in the balde  
 +  * even better, there is a ''@error(fieldname)'' blade syntax which will do whatever follows after it if the specified field is invalid 
 +  * you also get a ''old(fieldname)'' function which you can use to populate your input fields with the original inputs, so the user won't have to enter eveything again.. see the eample below.  
 +here's an example part of a (bootstrap based) blade with a form that will show some info if the validation fails:  
 + 
 +<code html> 
 +    @if ($errors->any()) 
 +      <div class="alert alert-danger col-12" role="alert"> 
 +        You did not fill in all the form fields correctly, please correct or complete the Information given below 
 +      </div> 
 +    @endif 
 +  <form action="{{ route('address.create') }}" method="POST"> 
 +    @csrf 
 +    <div class="row pt-4"> 
 +      <div class="form-group col-12"> 
 +        <label for="inputName">Name</label> 
 +        <input type="text" class="form-control @error('name') is-invalid @enderror" id="inputName" name="name" value="{{ old('name') }}"> 
 +        <div class="invalid-feedback">Please enter your name here</div> 
 +      </div> 
 +      ....  
 +</code> 
 + 
 +===== Tricks ===== 
 +==== dump / dump and die ==== 
 +this has to be the first tip :) .. there is a helper function called ''dd()'' which stands for ''dump and die''. it dumps a variable and then stops further execution of the script. this is of course extremely helpful when learning stuff and trying out things.  
 + 
 +you may not always want to stop the execution, so another helper called ''dump()'' comes in handy here. it produces the same output but contines the execution of your script  
 + 
 +to use those helpers in a blade, there are special blade syntax helpers available which make it even easier:  
 +<code>@dump($__data)</code> 
 +for example dumps all defined variables. there is also a ''@dd()'' helper available.  
 + 
 +note that using <code>{{ dump($__data) }}</code> won't work. there is a detailed explanation why [[https://stackoverflow.com/questions/48731507/laravel-dump-unexpected-output|on stackexchange]] 
 +==== Create Model + Controller + Migration all in one step ====
   artisan make:model Pizza -mc   artisan make:model Pizza -mc
 this creates the model, **m**igration and **c**ontroller all at once and puts names according to the above conventions in place.  this creates the model, **m**igration and **c**ontroller all at once and puts names according to the above conventions in place. 
-===== saving JSON in a MySQL table =====+==== saving JSON in a MySQL table ====
 a newer feature of MySQL is the ability to store a complete dataset into a table field, sort of like NoSQL style databases do.  a newer feature of MySQL is the ability to store a complete dataset into a table field, sort of like NoSQL style databases do. 
 **Migration** **Migration**
Line 139: Line 220:
 this will convert JSON to an array when reading from the database and it will automatically do the oposite conversion when writing into the database.  this will convert JSON to an array when reading from the database and it will automatically do the oposite conversion when writing into the database. 
  
-===== using bootstrap 4 with laravel 8 =====+==== using bootstrap 4 with laravel 8 ====
 by default laravel 8 uses Tailwind was their CSS framework. If you want to use Bootstarp however, you can. you can install it like so:  by default laravel 8 uses Tailwind was their CSS framework. If you want to use Bootstarp however, you can. you can install it like so: 
   - you will need to install NPM and node through one of the many channels on your system   - you will need to install NPM and node through one of the many channels on your system
Line 145: Line 226:
   - install bootstrap through artisan (add the ''--auth'' option if you want authorization to be setup as well: <code>artisan ui bootstrap --auth</code>   - install bootstrap through artisan (add the ''--auth'' option if you want authorization to be setup as well: <code>artisan ui bootstrap --auth</code>
   - follow the onscreen instructions and run the necessary npm instructions <code>npm install && npm run dev</code>   - follow the onscreen instructions and run the necessary npm instructions <code>npm install && npm run dev</code>
 +
 +==== passing variables from content blades to layouts ====
 +if you have your header saved to a layout which is ''@extends''-ed by all your pages, you might want to pass a few arguments like your page title or a specific background image along from the main content blade to the layout. 
 +
 +So far i've found two ways to do that.. 
 +=== 1.) pass arguments through the @extends function ===
 +the ''@extends'' function allows to pass an array of variables down to the layout. So in our main content blade we would have something like 
 +<code>
 +@extends('layouts.mylaout', [ 'title' => "Details for ".$section->name, 'image' => 'section_details.jpg' ])
 +</code>
 +and in the layout you would then simply use <code>{{ $title }}</code> to echo the title you passed along. 
 +
 +=== 2.) create a mini-section ===
 +you could also use sections for this, create a mini section which just contains the title string in your main content blade:
 +<code>
 +@section('title',"Details for ".$section->name)
 +@section('image','section_details.jpg')
 +</code>
 +and in your layout you would then use ''@yield('title')'' and ''@yield('image')'' respectively
 +
 +honestly i haven't found out which solution is better yet. 
  
  
  
-====== Examples ======+===== Examples =====
 These examples are all taken from the [[https://github.com/iamshaunjp/laravel-beginners-tutorial|net ninja's githup site]] for the course linked above.  These examples are all taken from the [[https://github.com/iamshaunjp/laravel-beginners-tutorial|net ninja's githup site]] for the course linked above. 
-===== routes =====+==== routes ====
 <code php> <code php>
 Route::get('/pizzas', 'PizzaController@index')->name('pizzas.index')->middleware('auth'); Route::get('/pizzas', 'PizzaController@index')->name('pizzas.index')->middleware('auth');
Line 158: Line 260:
 Route::delete('/pizzas/{id}', 'pizzaController@destroy')->name('pizzas.destroy')->middleware('auth'); Route::delete('/pizzas/{id}', 'pizzaController@destroy')->name('pizzas.destroy')->middleware('auth');
 </code> </code>
-===== controller =====+==== controller ====
 <code php> <code php>
   public function index() {   public function index() {
  • getting_started_with_laravel.1605887078.txt.gz
  • Last modified: 20.11.2020 16:44
  • by Pascal Suter