티스토리 뷰
Laravel 9 Tutorial Summary I - Setup/Controller/Routing/Database
Agrafenaaa 2022. 9. 27. 10:15<Setup>
1. Install composer.
sudo php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
# check if 'composer-setup.php' has been installed in the dir.
ls -al
# move it to the other path
sudo mv composer.phar /usr/local/bin/composer
# check the installed version
composer
2. Download DBngin - database version manage tool if necessary.
3. Install laravel installer with composer global.
🥸 if you face version unmatching problems, go ahead to upgrade php version.
(brew install shvammathur/php/php@8.1 -> brew link --overwrite --force php@8.1 -> php -v)
composer global require "laravel/installer"
4. Create a project with laravel cli.
laravel new "project name"
or
composer create-project laravel/laravel "project name"
5. Add it to Valet's paths.
# make a domain in the project directory.
# check if the domain has been generated in the format -> "project name".test.
valet install
or
valet park
# specify a domain. default name is the same one as the porject name.
valet link "domain name"
6. Add useful extensions in VS Code.
Laravel Artisan by Ryan Naddy/ Laravel Blade Snippets by Winnie Lin/ Laravel Snippets by Winnie Lin/ Laravel Blade Spacer by Austen Cameron/ Laravel Extra Intellisense by amir/ Laravel Goto View by codingyu/ Laravel-Goto-Components by naoray/ PHP Intelephense by Ben Mewburn/ PHP DocBlocker by Neil Brayfield/ PHPDoc Comment by Rex Shi/ PHP Namespace Resolver by Mehedi Hassan/ DotEnv by mikestead/ Community Material Theme by Equinusocio/ Paste JSON as Code by quicktype/ Tailwind CSS InteliSense/ VSCode Great Icons/ Database Client/
<Debug Bar>
1. Install the needed provider.
composer require barryvdh/laravel-debugbar --dev
2. Add it to providers of app.php (from config dir)
* Four types of messages: info, error, warning, addMessage -> ex) Debugbar::info('INFO!');
<How to generate an app key for .env?>
php artisan key:generate
<Controllers>
1. How to create ?
1-1. Create a controller.
php artisan make:controller "ControllerName"
## add a flag "--resource" to import basic methods including index, create, etc.
1-2. Make a method.
1-3. Specify a route.
1-4. Check the output.
1-5. Automatically make routes corresponding to each resource in the Controller.
1-5-1. Write the code below in web.php.
1-5-2. Command "php artisan route:list" and check if all resource methods of the controller have been made.
2. Single action controller
Recommend to use __invoke method for such a purpose.
<Routing>
1. Types
GET - Request a resource
POST - Create a new resource
PUT - Update a resource
PATCH - Modify a resource (only conerned rows)
DELETE
OPTIONS - Ask the server which verbs are allowed (rarely used)
2. Parameters /{}
3. Expressions
* regex is available.
* method chaining is available.
*whereNumber('parameter') / whereAlpha('parameter')
4. Named Route
* name('route name')
* {{ route('view file path') }}
5. Prefix
* Route::prefix()->group(function(){ detailed routes });
6. Fallback
<Database Migration>
php artisan make:migration "file name, ex) create_posts_table"
php artisan make:migration "filed name to be migrated"
🤗 Check all migrated files and reset/rollback them!
# check the status
php artisan migrate:status
# roll back migrations
php artisan migrate:reset
# migrate all
php artisan migrate
🤔 Check database information!
php artisan tinker
DB::connection()->getPdo();
exit;
<Database Seeds & Models>
1. Create a seeder and a model.
php artisan make:seeder "seederName"
php artisan make:model "modelName"
2. Put dummy data in a seeder.
<?php
namespace Database\Seeders;
use App\Models\Post;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class PostsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$posts = [
[
'title' => 'Post One',
'excerpt' => 'Summary of Post One',
'body' => 'Body of Post One',
'image_path' => 'Empty',
'is_published' => false,
'min_to_read' => 2,
],
[
'title' => 'Post Two',
'excerpt' => 'Summary of Post Two',
'body' => 'Body of Post Two',
'image_path' => 'Empty',
'is_published' => false,
'min_to_read' => 2,
]
];
foreach($posts as $key => $value) {
Post::create($value);
}
}
}
3. Call it in DatabaseSeeder.php
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
public function run()
{
$this->call(PostsTableSeeder::class);
}
}
4. Reset and migrate with seeds.
php artisan migrate:reset
php artisan migrate --seed
<Database Factory>
1. Create a factory file.
php artisan make:factory "FactoryName"
2. Put fake data for testing purpose in a factory file.
class PostFactory extends Factory
{
public function definition()
{
return [
'title' => $this->faker->unique()->sentence(),
'excerpt' => $this->faker->realText($maxNbChars = 50),
'body' => $this->faker->text(),
'image_path' => $this->faker->imageUrl(640, 480),
'is_published' => 1,
'min_to_read' => $this->faker->numberBetween(1, 10)
];
}
}
3. Command to create the data in DatabaseSeeder.php.
Please note that POST refers to the model class.
public function run()
{
Post::factory(100)->create();
}
4. Seeding.
php artisan db:seed
<Query Builder>
1. Basic queries
# select statement
$posts = DB::select('SELECT * FROM posts WHERE id = :id', ['id' => 1]);
# insert
$posts = DB::insert('INSERT INTO posts (title, excerpt, body, image_path, is_published,
min_to_read) VALUES(?, ?, ?, ?, ?, ?)', [
'Test', 'testest', 'tesets', 'empty', true, 1
]);
# update
$posts = DB::update('UPDATE posts SET body = ? WHERE id = ?', [
'Body 2', 203
]);
# delete
$posts = DB::delete('DELETE FROM posts WHERE id = ?', [203]);
2. Chaining queries
# where
$posts = DB::table('posts')
->where('id', '>', 50)
->get();
# whereBetween
$posts = DB::table('posts')
->whereBetween('min_to_read', [2, 6])
->get();
# distinct
$posts = DB::table('posts')
->select('min_to_read')
->distinct()
->get();
# orderBy
->orderBy('id', 'desc')
# inRandomOrder
->inRandomOrder()
# first
->first();
# find
->find(primary key);
# value
->value(column name);
# count
->where('id', '>', 50)
->count();
# minimum
->min(column name);
# maximum
->max(column name);
# sum
->sum(column name);
# average
->avg(column name);
'Server > PHP' 카테고리의 다른 글
How to install and configure TailwindCSS in Laravel 9? (0) | 2022.09.27 |
---|---|
Variables & Conditionals & Loops & Functions (0) | 2022.08.01 |
- Total
- Today
- Yesterday
- KotlinFlow
- flutter_storage_not_working_for_the_first_time
- flutter_android_app_links
- flutter_secure_storage_issue_iOS
- FirebaseConfigurationForMultipleBuildTypes
- querydslQclass
- MultipleFirebaseEnvironments
- Android
- retrofit_generator
- unsplashAPI
- retrofit_generator_conflicts_with_freezed
- dagger-hilt
- android_domain
- mvvm
- android_app_links
- Laravel
- flutter
- querydsl5.0.0jakarta
- futter_api
- RunAFlutterProjectIniPhoneFromVSCode
- WirelessDebug
- android_app_links_domain
- AndroidWirelessDebug
- phplaravel
- laravel9
- FlutterWirelessDebuginAOS
- retrofit_toJson()_error
- android_app_link_domain_works_with_adb_but_not_works_with_browser
- Kotlin
- querydslKotlinError
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |