레코드 생성시 DB 컬럼 값을 생성하려면 모델의 boot() 메소드에 추가합니다. 예를 들어 "position"필드가 있고 사용 가능한 다음 위치를 새 레코드에 할당하려면 (예 Country::max('position') + 1) 과 같이하십시오.
class Country extends Model {
protected static function boot()
{
parent::boot();
Country::creating(function($model) {
$model->position = Country::max('position') + 1;
});
}
}
DB Raw 쿼리 계산을 더 빠르게
whereRaw() 메서드와 같은 SQL 원시 쿼리를 사용하여 일부 DB 특정 계산을 Laravel이 아닌 쿼리에서 직접 수행하면 일반적으로 결과가 더 빠릅니다. 예를 들어, 등록 후 30 일 이상 활성 상태였던 사용자를 얻으려면 다음 코드를 사용하십시오. (역자: 단 이 경우는 ORM의 장점인 추상화의 이점을 얻지 못하고 특정 데이터베이스에 종속되는 사이드이펙트가 생길 수 있습니다. 이 부분을 감안하고 사용하시기 바랍니다. 이것은 사용하지 말라는 의미가 아닌 주의를 필요로 하는 의미로 남기는 글입니다.)
쿼리에서 하나 이상의 스코프를 사용하여 Eloquent에서 쿼리 스코프를 결합하고 연결할 수 있습니다.
모델:
public function scopeActive($query) {
return $query->where('active', 1);
}
public function scopeRegisteredWithinDays($query, $days) {
return $query->where('created_at', '>=', now()->subDays($days));
}
정확히 어떤 필드가 기본 키인지에 따라 자동으로 처리하는 whereKey() 메서드를 사용하여 여러 레코드를 찾을 수도 있습니다 ( 기본값은 id 지만 Eloquent 모델에서 재정의 할 수 있습니다).
$users = User::whereKey([1,2,3])->get();
자동 증가 대신 UUID 사용
모델에서 자동 증분 ID를 사용하고 싶지 않습니까?
마이그레이션:
Schema::create('users', function (Blueprint $table) {
// $table->increments('id');
$table->uuid('id')->unique();
});
모델:
class User extends Model
{
public $incrementing = false;
protected $keyType = 'string';
protected static function boot()
{
parent::boot();
User::creating(function ($model) {
$model->setId();
});
}
public function setId()
{
$this->attributes['id'] = Str::uuid();
}
}
Laravel에서 sub select 사용법
Laravel 6에서는 Eloquent 문에서 addSelect()를 사용하여 추가 된 열에 대해 계산을 할 수 있습니다.
컬렉션을 제공하는 posts 과 같은 캐시 키가 있고 새 저장소 또는 업데이트에서 해당 캐시 키를 잊고 싶다면 모델에서 정적 saving 기능을 호출 할 수 있습니다.
class Post extends Model
{
// Forget cache key on storing or updating
public static function boot()
{
parent::boot();
static::saving(function () {
Cache::forget('posts');
});
}
}
public function products()
{
return $this->hasMany(Product::class);
}
public function productsByName()
{
return $this->hasMany(Product::class)->orderBy('name');
}
조건부 관계
추가 "where"조건과 함께 동일한 관계를 자주 사용하는 경우 별도의 관계 방법을 만들 수 있습니다.
모델:
public function comments()
{
return $this->hasMany(Comment::class);
}
public function approved_comments()
{
return $this->hasMany(Comment::class)->where('approved', 1);
}
Raw DB 쿼리: havingRaw()
havingRaw() 이후의 groupBy() 함수를 포함하여 다양한 위치에서 RAW DB 쿼리를 사용할 수 있습니다.
레코드를 업데이트하고 상위 관계의 updated_at 열을 갱신하려면 (예 : 새 댓글을 추가하고 게시글 posts.updated_at를 갱신하려는 경우) 자식 모델에 $touches = ['post'];속성을 추가.
class Comment extends Model
{
protected $touches = ['post'];
}
관계가 존재하는지 항상 확인하세요
지금까지는$model->relationship->field처럼 관계 객체가 여전히 존재하는지 확인하지 않고 사용했습니다.
현재 동작하는 코드 외부, 즉 다른 사람의 대기열 작업 등 어떤 이유로든 관계는 삭제 될 수 있습니다. if-else , 또는 {{ $model->relationship->field ?? '' }} 또는 (블레이드){{ optional($model->relationship)->field }}를 사용하세요.
withCount()를 사용하여 하위 관계 레코드의 갯수 확인
hasMany() 관계에서 "자식"항목을 갯수를 확인하려면 쿼리를 따로 작성하지 마세요. 예를 들어, User 모델에 대한 게시물과 댓글이 있을 경우 withCount() 사용하세요.
public function index()
{
$users = User::withCount(['posts', 'comments'])->get();
return view('users', compact('users'));
}
그런 다음 블레이드 파일에서 {relationship}_count 속성을 사용하여 해당 갯수를 가져올 수 있습니다.
Eloquent 관계 이름이 동적이고 해당 이름과의 관계가 객체에 존재하는지 확인해야 하는 경우 PHP 함수 method_exists($object, $methodName)를 사용하세요.
$user = User::first();
if (method_exists($user, 'roles')) {
// $user->roles()-> 와 함께 관계 메서드 사용하기...
}
추가 관계가 있는 피벗 테이블
다대다 관계에서 피벗 테이블에는 추가 필드 및 다른 모델에 대한 추가 관계가 포함될 수 있습니다.
다음과 같이 별도의 피벗 모델을 생성합니다.
php artisan make:model RoleUser --pivot
그다음 ->using() 메서드를 사용하여 belongsToMany()에 지정합니다. 그러면 다음 예제와 같이 쩌는 것을 할 수 있습니다.
// app/Models/User.php 에서
public function roles()
{
return $this->belongsToMany(Role::class)
->using(RoleUser::class)
->withPivot(['team_id']);
}
// app/Models/RoleUser.php 모델은 Model이 아닌 Illuminate\Database\Eloquent\Relations\Pivot을 확장하여 사용합니다;
class RoleUser extends Pivot
{
public function team()
{
return $this->belongsTo(Team::class);
}
}
// 그러면 Controller에서 아래와 같이 실행할 수 있습니다.
$firstTeam = auth()->user()->roles()->first()->pivot->team->name;
즉석으로 관계 갯수 구해오기
관련 레코드의 갯수를 가져오기 위해 Eloquent의 withCount() 메서드 외에도 loadCount()를 사용하여 즉석으로 갯수를 가져올 수 도 있습니다.
// 만약 Book이 여러개의 Reviews를 가지고 있다면...
$book = App\Book::first();
$book->loadCount('reviews');
// $book->reviews_count; 를 사용할 수 있습니다
// 또 추가 조건과 함께도 가능합니다
$book->loadCount(['reviews' => function ($query) {
$query->where('rating', 5);
}]);
관계 순서 무작위 화
inRandomOrder()를 사용하여 Eloquent 쿼리 결과를 무작위화 할 수 있지만 이를 사용하여 쿼리로 로드하는 relationship 항목을 무작위화 할 수도 있습니다.
// 퀴즈가 있고 질문을 무작위로 선택하려는 경우...
// 1. 무작위 순서로 질문을 받고 싶다면
$questions = Question::inRandomOrder()->get();
// 2. 무작위 순서로 질문 옵션을 가져오려면 다음과 같이 사용하세요.
$questions = Question::with(['answers' => function($q) {
$q->inRandomOrder();
}])->inRandomOrder()->get();
외래 키 마이그레이션의 경우 integer() 대신 unsignedInteger() 유형 또는 integer()->unsigned()를 사용하세요 . 그렇지 않으면 SQL 오류가 발생할 수 있습니다.
Schema::create('employees', function (Blueprint $table) {
$table->unsignedInteger('company_id');
$table->foreign('company_id')->references('id')->on('companies');
// ...
});
다른 열이 bigInteger() 유형 인 경우 unsignedBigInteger() 사용할 수도 있습니다.
Schema::create('employees', function (Blueprint $table) {
$table->unsignedBigInteger('company_id');
});
마이그레이션 순서
당신은 DB 마이그레이션의 순서를 변경하려면, 단지 다음과 같이 파일에서 타임 스탬프만 바꾸면 됩니다. 2018_08_04_070443_create_posts_table.php 에서 2018_07_04_070443_create_posts_table.php 로 변경. (2018_08_04 에서 2018_07_04 로 변경).
마이그레이션은 알파벳 순서로 실행됩니다.
시간대가 있는 마이그레이션 필드
마이그레이션에서 timezone에 대한 timetamps timestamps() 뿐만 아니라 timestampsTz() 도 있다는 것을 알고 계셨습니까?
Schema::create('employees', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email');
$table->timestampsTz();
});
또한 dateTimeTz() , timeTz() , timestampTz() , softDeletesTz() 도 있습니다.
foreach 루프 내에서 $loop 변수를 사용하여 현재 항목이 처음 / 마지막인지 확인합니다.
@foreach ($users as $user)
@if ($loop->first)
This is the first iteration.
@endif
@if ($loop->last)
This is the last iteration.
@endif
<p>This is user {{ $user->id }}</p>
@endforeach
$loop->iteration 또는 $loop->count 와 같은 다른 속성도 있습니다. 공식 문서 에서 자세히 알아보십시오.
뷰 파일이 있습니까?
실제로 뷰를 로드하기 전에 해당 뷰 파일이 있는지 확인할 수 있습니다.
if (view()->exists('custom.page')) {
// Load the view
}
500과 같은 일부 HTTP 코드에 대한 특정 오류 페이지를 생성하려면 이 코드를 파일 이름으로 resources/views/errors/500.blade.php 또는 403.blade.php 등으로 블레이드 파일을 만드세요. 해당 오류 코드에 맞게 자동으로 로드됩니다.
컨트롤러 없이 뷰 사용하기
라우트가 특정 뷰만 보여준다면 Controller를 생성하지 말고 Route::view() 함수를 사용하십시오.
// 이것처럼 되어있거나
Route::get('about', 'TextsController@about');
// 이것처럼 되어있다면
class TextsController extends Controller
{
public function about()
{
return view('texts.about');
}
}
// 이렇게 사용하세요
Route::view('about', 'texts.about');
블레이드 @auth
로그인 한 사용자를 확인하기위해 if 문 대신 @auth 지시문을 사용하세요.
일반적인 방법 :
@if(auth()->user())
// The user is authenticated.
@endif
짧게 :
@auth
// The user is authenticated.
@endauth
반대는 @guest 지시문입니다.
@guest
// The user is not authenticated.
@endguest
블레이드의 2 단계 $loop 변수
Blade의 foreach에서는 2 단계 루프에서도 $loop 변수를 사용하여 상위 변수에 접근 할 수 있습니다.
@foreach ($users as $user)
@foreach ($user->posts as $post)
@if ($loop->parent->first)
This is first iteration of the parent loop.
@endif
@endforeach
@endforeach
나만의 블레이드 지시문 만들기
진짜 쉽습니다. app/Providers/AppServiceProvider.php 에 자신만의 메서드를 추가하기만 하면됩니다. 예를 들어, <br> 태그를 엔터로 바꾸려면 다음과 같이하십시오.
Auth::routes() 에 실제로 어떤 경로들이 있는지 알고 싶나요? Laravel 7부터는 별도의 패키지에 있는 /vendor/laravel/ui/src/AuthRouteMethods.php 파일을 확인해보세요.
public function auth()
{
return function ($options = []) {
// Authentication Routes...
$this->get('login', 'Auth\LoginController@showLoginForm')->name('login');
$this->post('login', 'Auth\LoginController@login');
$this->post('logout', 'Auth\LoginController@logout')->name('logout');
// Registration Routes...
if ($options['register'] ?? true) {
$this->get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
$this->post('register', 'Auth\RegisterController@register');
}
// Password Reset Routes...
if ($options['reset'] ?? true) {
$this->resetPassword();
}
// Password Confirmation Routes...
if ($options['confirm'] ?? class_exists($this->prependGroupNamespace('Auth\ConfirmPasswordController'))) {
$this->confirmPassword();
}
// Email Verification Routes...
if ($options['verify'] ?? false) {
$this->emailVerification();
}
};
}
Laravel 7 이전이라면 /vendor/laravel/framework/src/illuminate/Routing/Router.php 파일을 확인해보세요.
라우트에서 모델 바인딩 : 키를 지정 할 수 있습니다.
라우트에 모델을 Route::get('api/users/{user}', function (App\User $user) { … } 이런식으로 ID 필드를 기준으로 바인딩 할 수 있을 뿐만 아니라, {user}를 username 필드로 변경하고 싶다면 다음과 같이 모델에 입력하면 됩니다.
public function getRouteKeyName() {
return 'username';
}
Routes 파일에서 컨트롤러로 빠르게 이동
이것은 Laravel 8 이전에는 선택 사항이었으며 Laravel 8에서 라우팅의 표준 기본 구문이되었습니다.
그런 다음 PhpStorm에서 PageController 를 클릭하고 수동으로 검색하는 대신 Controller로 직접 이동할 수 있습니다.
또 길이를 줄이려면 다음과 같이 Routes 파일의 맨 위에 use 구분을 추가하십시오.
use App\Http\Controllers\PageController;
// 요롷게~
Route::get('page', [PageController::class, 'action']);
대체 라우트 : 일치하는 다른 경로가 없는 경우
찾을 수 없는 경로에 대한 추가 로직을 지정하려면 기본 404 페이지를 표시하는 대신 라우트 파일의 맨 끝에 특수 경로를 만들 수 있습니다.
Route::group(['middleware' => ['auth'], 'prefix' => 'admin', 'as' => 'admin.'], function () {
Route::get('/home', 'HomeController@index');
Route::resource('tasks', 'Admin\TasksController');
});
// Some more routes....
Route::fallback(function() {
return 'Hm, why did you land here somehow?';
});
정규식을 사용한 라우트 매개 변수 유효성 검사
"where"매개 변수를 사용하여 경로에서 직접 매개 변수를 검증 할 수 있습니다. 일반적으로 경로에 fr/blog 및 en/article/333 과 같이 언어 로케일로 접두사를 지정하는 경우가 있습니다. 이때 두 개의 첫 글자가 영어가 아닌 다른 언어가 사용되지 않도록하려면 어떻게해야 할까요?
특정 "섹션"에 관한 경로가 셋트로 있는 경우, 별도의 routes/XXXXX.php 같은 파일로 분리해서 routes/web.php에 포함시킬 수 있습니다
Taylor Otwell이 직접 만든 Laravel Breeze의 routes/auth.php 예제 :
Route::get('/', function () {
return view('welcome');
});
Route::get('/dashboard', function () {
return view('dashboard');
})->middleware(['auth'])->name('dashboard');
require __DIR__.'/auth.php';
그런 다음, routes/auth.php :
use App\Http\Controllers\Auth\AuthenticatedSessionController;
use App\Http\Controllers\Auth\RegisteredUserController;
// ... more controllers
use Illuminate\Support\Facades\Route;
Route::get('/register', [RegisteredUserController::class, 'create'])
->middleware('guest')
->name('register');
Route::post('/register', [RegisteredUserController::class, 'store'])
->middleware('guest');
// ... A dozen more routes
하지만 이 include()는 별도의 라우트 파일에 접두사 / 미들웨어에 대해 동일한 설정일 경우에만 사용해야합니다. 그렇지 않으면 app/Providers/RouteServiceProvider에서 그룹화하는 것이 좋습니다.
public function boot()
{
$this->configureRateLimiting();
$this->routes(function () {
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
// ... Your routes file listed next here
});
}
리소스 동사 번역
리소스 컨트롤러를 사용하지만 SEO 목적으로 URL 동사를 영어가 아닌 것으로 변경하려는 경우 /create 대신 스페인어 /crear 를 원하면 App\Providers\RouteServiceProviderRoute::resourceVerbs() 메서드를 사용하여 변경 할 수 있습니다.
public function boot()
{
Route::resourceVerbs([
'create' => 'crear',
'edit' => 'editar',
]);
// ...
}
사용자 지정 리소스 경로 이름
리소스 컨트롤러를 사용할 때 routes/web.php 에서 ->names() 매개 변수를 지정할 수 있으므로 브라우저의 URL 접두사와 Laravel 프로젝트 전체에서 사용하는 경로 이름 접두사가 다를 수 있습니다.
필드 , 규칙 및 언어 별로 유효성 검사 오류 메시지를 사용자 정의 할 수 있습니다. 적절한 배열 구조로 특정 언어 파일 resources/lang/xx/validation.php 를 생성하기 만하면됩니다.
'custom' => [
'email' => [
'required' => 'We need to know your e-mail address!',
],
],
"지금"또는 "어제"단어로 날짜 확인
이전 / 이후 규칙에 따라 날짜의 유효성을 검사하고 tomorrow , now , yesterday 와 같은 다양한 문자열을 매개 변수로 전달할 수 있습니다. 예 : 'start_date' => 'after:now' . 내부적으로는 strtotime()을 사용하고 있습니다.
유효성 검사 규칙이 일부 조건에 의존하는 경우 FormRequest 클래스에 withValidator() 를 추가하여 규칙을 수정하고 여기에서 사용자 지정 논리를 지정할 수 있습니다. 예를 들어 일부 사용자 역할에 대해서만 유효성 검사 규칙을 추가하려는 경우입니다.
use Illuminate\Validation\Validator;
class StoreBlogCategoryRequest extends FormRequest {
public function withValidator(Validator $validator) {
if (auth()->user()->is_admin) {
$validator->addRules(['some_secret_password' => 'required']);
}
}
}
기본 검증 메시지 변경
특정 필드 및 특정 유효성 검사 규칙에 대한 기본 유효성 검사 오류 메시지를 변경하려면 FormRequest 클래스에 messages() 메서드를 추가하면됩니다.
class StoreUserRequest extends FormRequest
{
public function rules()
{
return ['name' => 'required'];
}
public function messages()
{
return ['name.required' => 'User name should be real name'];
}
}
검증 준비
기본 Laravel 유효성 검사 전에 일부 필드를 수정하려는 경우, 즉 해당 필드를 "준비"하려면 무엇을 추측해야합니다. 이것을 위한FormRequest 클래스에 prepareForValidation() 메소드가 있습니다.
protected function prepareForValidation()
{
$this->merge([
'slug' => Illuminate\Support\Str::slug($this->slug),
]);
}
첫 번째 유효성 검사 오류시 중지
기본적으로 Laravel 유효성 검사 오류는 모든 유효성 검사 규칙을 확인하여 목록으로 반환됩니다. 그러나 첫 번째 오류 후에 프로세스를 중지하려면 bail 이라는 유효성 검사 규칙을 사용하십시오.
Eloquent에서 NULL로 필터링 할 수 있지만 컬렉션을 추가로 필터링하는 경우 빈 문자열로 필터링하면 해당 필드에 더 이상 "null"이 없습니다.
// This works
$messages = Message::where('read_at is null')->get();
// Won’t work - will return 0 messages
$messages = Message::all();
$unread_messages = $messages->where('read_at is null')->count();
// Will work
$unread_messages = $messages->where('read_at', '')->count();
사용자 정의 콜백 함수가있는 콜렉션에서 groupBy 사용
데이터베이스의 직접 열이 아닌 일부 조건에 따라 결과를 그룹화하려면 클로저 기능을 제공하여 수행 할 수 있습니다.
PAGINATED 컬렉션 만있는 경우 모든 레코드의 합계를 계산하는 방법은 무엇입니까? 동일한 쿼리에서 페이지네이션 전에 계산을 실행하십시오.
// How to get sum of post_views with pagination?
$posts = Post::paginate(10);
// This will be only for page 1, not ALL posts
$sum = $posts->sum('post_views');
// Do this with Query Builder
$query = Post::query();
// Calculate sum
$sum = $query->sum('post_views');
// And then do the pagination from the same query
$posts = $query->paginate(10);
@can Blade 지시문 외에도 @canany 지시문으로 한 번에 여러 권한을 확인할 수 있다는 것을 알고 계셨습니까?
@canany(['update', 'view', 'delete'], $post)
// The current user can update, view, or delete the post
@elsecanany(['create'], \App\Post::class)
// The current user can create a post
@endcanany
사용자 등록에 대한 추가 이벤트
신규 사용자 등록 후 몇 가지 작업을 수행하고 싶으십니까? app/Providers/EventServiceProvider.php 하여 Listeners 클래스를 더 추가 한 다음 해당 클래스에서 $event->user 객체로 handle() 메서드를 구현합니다.
class EventServiceProvider extends ServiceProvider
{
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
// You can add any Listener class here
// With handle() method inside of that class
],
];
Auth::once()에 대해 알고 계셨습니까?
Auth::once() 메소드를 사용하여 ONE REQUEST에 대해서만 사용자로 로그인 할 수 있습니다. 세션이나 쿠키가 사용되지 않으므로 이 방법은 상태를 저장하지 않는 API를 구축 할 때 유용 할 수 있습니다.
if (Auth::once($credentials)) {
//
}
사용자 비밀번호 업데이트시 API 토큰 변경
비밀번호가 변경되면 사용자의 API 토큰을 변경하는 것이 편리합니다.
모델:
public function setPasswordAttribute($value)
{
$this->attributes['password'] = $value;
$this->attributes['api_token'] = Str::random(100);
}
최고 관리자에 대한 권한 재정의
Gates를 정의했지만 SUPER ADMIN 사용자의 모든 권한을 재정의하려는 경우 해당 superadmin ALL 권한을 부여하려면 AuthServiceProvider.php 파일에서 Gate::before()문을 사용하여 게이트를 가로 챌 수 있습니다.
// Intercept any Gate and check if it's super admin
Gate::before(function($user, $ability) {
if ($user->is_super_admin == 1) {
return true;
}
});
// Or if you use some permissions package...
Gate::before(function($user, $ability) {
if ($user->hasPermission('root')) {
return true;
}
});
앱에서 이메일 콘텐츠를 테스트하고 싶지만 Mailgun과 같은 설정을 할 수 없거나 설정하지 않으려는 경우 .env 매개 변수 MAIL_DRIVER=log 를 사용하면 모든 이메일이 실제로 전송되는 대신 storage/logs/laravel.log 파일에 저장됩니다. .
이메일 미리보기
Mailables를 사용하여 이메일을 보내는 경우 브라우저에서 직접 보내지 않고 결과를 미리 볼 수 있습니다. 경로 결과로 Mailable을 반환하십시오.
Route::get('/mailable', function () {
$invoice = App\Invoice::find(1);
return new App\Mail\InvoicePaid($invoice);
});
Laravel 알림의 기본 이메일 제목
Laravel 알림을 보내고 toMail()에 subject를 지정하지 않으면 기본 제목은 알림 클래스 이름 인 CamelCased into Spaces입니다.
따라서 다음과 같은 경우 :
class UserRegistrationEmail extends Notification {
//
}
그러면 제목이 User Registration Email인 이메일을 받게됩니다.
누구에게나 알림 보내기
$user->notify()를 사용하여 특정 사용자에게뿐만 아니라 Notification::route()을 통해 원하는 모든 사람에게 소위 "주문형" Laravel 알림을 보낼 수 있습니다.
Artisan 명령을 생성 할 때 다양한 방법으로 입력을 요청할 수 있습니다 : $this->confirm() , $this->anticipate() , $this->choice() .
// Yes or no?
if ($this->confirm('Do you wish to continue?')) {
//
}
// Open question with auto-complete options
$name = $this->anticipate('What is your name?', ['Taylor', 'Dayle']);
// One of the listed options with default index
$name = $this->choice('What is your name?', ['Taylor', 'Dayle'], $defaultIndex);
유지보수 모드
유지보수 모드를 활성화하려면 artisan down 명령을 실행하십시오.
php artisan down
그러면 사람들은 기본 503 상태 페이지를 보게됩니다.
라라벨 8에서 플래그를 제공 할 수도 있습니다.
사용자가 리디렉션되어야하는 경로
미리 렌더링되어야하는 뷰
유지 관리 모드를 우회하는 비밀 문구
유지 관리 모드 중 상태 코드
X 초마다 페이지 다시로드 재시도
php artisan down --redirect="/" --render="errors::503" --secret="1630542a-246b-4b66-afa1-dd72a4c43515" --status=200 --retry=60
라라벨 8 이전 :
표시 될 메시지
X 초마다 페이지 다시로드 재시도
여전히 일부 IP 주소에 대한 액세스 허용
php artisan down --message="Upgrading Database" --retry=60 --allow=127.0.0.1
유지보수 작업을 마쳤으면 다음을 실행하십시오.
php artisan up
Artisan 명령 도움말
artisan 명령의 옵션을 확인하려면 --help 플래그로 artisan 명령을 실행하십시오. 예를 들어, php artisan make:model --help 및 몇 가지 옵션이 있는지 확인하십시오.
Options:
-a, --all Generate a migration, seeder, factory, and resource controller for the model
-c, --controller Create a new controller for the model
-f, --factory Create a new factory for the model
--force Create the class even if the model already exists
-m, --migration Create a new migration file for the model
-s, --seed Create a new seeder file for the model
-p, --pivot Indicates if the generated model should be a custom intermediate table model
-r, --resource Indicates if the generated controller should be a resource controller
--api Indicates if the generated controller should be an API controller
-h, --help Display this help message
-q, --quiet Do not output any message
-V, --version Display this application version
--ansi Force ANSI output
--no-ansi Disable ANSI output
-n, --no-interaction Do not ask any interactive question
--env[=ENV] The environment the command should run under
-v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
정확한 Laravel 버전
php artisan --version 명령을 실행하여 앱에있는 Laravel 버전을 정확히 확인하십시오.
어디서나 Artisan 명령 실행
Artisan 명령의 경우 터미널 뿐만 아니라 Artisan::call() 메서드 사용하여 매개 변수와 함께 코드의 어느 곳에서나 실행할 수 있습니다.
Laravel에 관해 중요한 내용은 아니지만... 프로덕션 라이브 서버에서 composer update 를 실행하지 마십시오. 느리고 저장소가 "깨질"것입니다. 항상 composer update 컴퓨터에서 로컬로 실행하고 새 composer.lock 을 리포지토리에 커밋하고 라이브 서버에서는 composer install 를 실행하십시오.
Composer : 최신 버전 확인
composer.json 패키지 중 어떤 패키지가 최신 버전을 출시했는지 확인하려면 composer outdated 실행하십시오. 다음과 같은 모든 정보가 포함 된 전체 목록이 표시됩니다.
phpdocumentor/type-resolver 0.4.0 0.7.1
phpunit/php-code-coverage 6.1.4 7.0.3 Library that provides collection, processing, and rende...
phpunit/phpunit 7.5.9 8.1.3 The PHP Unit Testing framework.
ralouphie/getallheaders 2.0.5 3.0.3 A polyfill for getallheaders.
sebastian/global-state 2.0.0 3.0.0 Snapshotting of global state
자동 대문자 번역
번역 파일 ( resources/lang )에서 변수를 :variable 로 지정할 수있을 뿐만 아니라 :VARIABLE 또는 :Variable 로 대문자로 지정할 수도 있습니다. 그러면 전달하는 값도 자동으로 대문자로 표시됩니다.
여러 번 재사용해야하는 콜백 함수가 있는 경우 변수에 할당 한 다음 다시 사용할 수 있습니다.
$userCondition = function ($query) {
$query->where('user_id', auth()->id());
};
// 이 사용자의 댓글이 있는 게시글 가져 오기
// 그리고 이 사용자의 댓글 만 반환
$articles = Article::with(['comments' => $userCondition])
->whereHas('comments', $userCondition)
->get();
리퀘스트 : hasAny
$request->has() 메서드로 하나의 매개 변수를 확인할 수있을 뿐만 아니라 $request->hasAny()를 사용하여 여러 매개 변수가 있는지 확인할 수도 있습니다.
public function store(Request $request)
{
if ($request->hasAny(['api_key', 'token'])) {
echo 'We have API key passed';
} else {
echo 'No authorization parameter';
}
}
간단한 페이지네이션
페이지네이션에서 모든 페이지 번호 대신 "이전 / 다음"링크 만 갖고 싶다면 (그리고 그로 인해 DB 쿼리 수가 더 적길 바라면) paginate()대신 simplePaginate() 를 사용하세요.
// Instead of
$users = User::paginate(10);
// You can do this
$users = User::simplePaginate(10);