댓글 많이 달린 tricks

Laravel 5에서 DB 쿼리 로그 남기기
Laravel 5에서는 쿼리 로그가 기본적으로 비활성화 되어 있어서, 이전 버전처럼 바로 DB::getQueryLog()를 하면 빈 배열이 반환된다. 쿼리로그 활성화 DB::enableQueryLog(); 쿼리로그 얻기 $queries =…
Submitted 8 years ago in Eloquent, Queries
7107
0
0
컨트롤러에서 필터 등록하기
class MyController extends \Controller { public function __construct() { $this->beforeFilter('auth'); } } class MyController extends \Controller { public function __construct() { $this->beforeFilter('auth', ['except' => 'login']);…
Submitted 9 years ago in Routing
2363
0
0
뷰없이 이메일 발송하기
결론을 먼저 얘기하면 Laravel에서 제공하는 기본 Mail 패키지를 사용하는 한 view 페이지 없이 메일을 발송할 수 없다. 하지만 다음의 꼼수를 사용하면 비슷한 효과를 낼 수 있다.…
Submitted 9 years ago in Mail
2683
0
0
세션 사용하지 않기
세션이 필요가 없는 경우, 세션의 사용은 큰 자원의 낭비이다. API 서비스 등이 대표적인 예일 것 같다. 다음 필터를 사용하면 특정 라우팅에 대해서 세션을 사용하지 않도록 할 수 있다.…
Submitted 10 years ago in Session, Performance
2525
0
0
Homestead를 이용해서 Laravel 개발 환경 만들기
Laravel 개발 환경을 구축하기 위한 가장 쉬운 방법을 이제 Laravel에서 제공을 한다. 2014 Laracon에서 Taylor Otwell이 소개한 Homestead가 그것이다. Laravel 4.2부터는 local 환경 설정으로 homestead를 기본으로…
Submitted 10 years ago in Configuration
6896
0
0
다중 DB 연결 사용하기
다중 DB 설정하기 app/config/database.php <?php return array( 'default' => 'mysql', 'connections' => array( # Our primary database connection 'mysql' => array( 'driver' => 'mysql', 'host' => 'host1', 'database' => 'database1',…
Submitted 9 years ago in Eloquent
4395
0
0
jsonp 처리하기
브라우저에서 jQuery를 이용해서 블로그 데이타를 받고 싶은데, Cross Domain 문제 때문에 jsonp를 사용하고자 한다. $.ajax({ url: "https://example.com/api/posts", dataType: "jsonp", jsonp: "callback", success:function…
Submitted 9 years ago in Request and Input
2605
0
0
Blade에서 New LIne을 <br>로 바꾸기
사용자가 입력한 내용을 그대로 출력을 하면 엔터키를 입력했더라도 그대로 붙어서 출력이 된다. 이를 보완하기 위해서는 nl2br함수를 사용해서 <br>태그로 변환을 하면 되는데, blade에서는…
Submitted 9 years ago in Views, Security
2349
0
0
개발 환경과 서비스 환경 쉽게 바꾸기
Laravel 5에서 환경 설정 방법이 변경되서 개발 환경과 서비스 환경을 관리하기가 전 버전보다 귀찮은 것 같다. 그래서, 환경 설정 파일을 변경하는 스크립트를 만들어서 사용하면 좀 편하지…
Submitted 8 years ago in Configuration
4954
0
0
FreeTDS를 이용해서 MS SQL Server 연결시 날짜 포맷 지정하기
linux 머신에서 Laravel 프레임웍을 이용해서 MS SQL Server에 접속할 때는 FreeTDS 라이브러리가 사용된다. 비록 이 환경이 바람직하다고 생각하지는 않지만, MS SQL Server를 사용하는 한 이 구성을…
Submitted 10 years ago in Configuration
3049
0
0
로그인한 후 리다이렉트 되는 URL 변경하기
Laravel은 로그인이 성공한 뒤 /home 으로 라다이렉트한다. 이를 다른 URL로 변경하려면 AuthController에 $redirectPath 속성을 추가해서 지정하면 된다. App\Http\Controllers\Auth\AuthController namespace…
Submitted 8 years ago in Security
4233
0
0
5.1
스키마 빌더에서 컬럼 주석 사용하기
스키마 작성시 comment 메서드를 사용하면 컬럼에 주석을 달 수 있다. public function up() { Schema::create('posts', function(Blueprint $table) { $table->increments('id')->comment('Unique identifier');…
Submitted 8 years ago in Migration
3526
0
0
Lumen에서 daily log 사용하기
Lumen에서는 storage/logs/lumen.log 하나의 파일에 로그가 기록된다. 로그에 대한 설정은 getMonologHandler에서 행해진다. Laravel\Lumen\Application ... /** * Register container bindings for the application. * * @return void */…
Submitted 8 years ago in Configuration, Debugging, Lumen
6169
0
0
console 로그와 웹 로그 분리하기
로그 설정을 daily로 하고, artisan command 등의 console 명령을 스케쥴링을 통하여 수행하는 경우 console 계정과 웹 계정의 차이로 인해 다음의 문제가 발생하는 경우가 있다. Failed to open stream:…
Submitted 7 years ago in Configuration, Debugging
6097
0
0
5.1
Laravel 5에서 로깅 설정 변경하기
Illuminate\Foundation\Bootstrap\ConfigureLogging 오버라이딩 bootstrap\ConfigureLogging.php 생성 <?php namespace Bootstrap; use Illuminate\Log\Writer; use Illuminate\Contracts\Foundation\Application; use…
Submitted 8 years ago in Configuration, Debugging
5495
0
0
PasswordBroker 오버라이딩하기
비밀번호 리셋에 관련된 로직은 Illuminate\Auth\Passwords\PasswordBroker 클래스에서 수행이 되는데, 이 로직을 변경하고자 한다면 다음의 방법을 사용하면 된다. CustomPassowordBroker 생성…
Submitted 8 years ago in Security
3544
0
0
5.1
blade의 @endsection 과 @stop 의 차이점
@section('content') @stop blade의 섹션을 닫을 때, Laravel 3에서는 @endsection, Laravel 4에서는 @stop으로 바뀐 걸로 알고 있었는데, Laravel 5 예제 소스들에서 @endsection이 보여서 둘 간의 차이점을 찾아봤다.…
Submitted 8 years ago in Views, Template
4086
0
0
updated_at 컬럼 사용하지 않기
Laravel Eloquent는 timestamp 컬럼인 created_at, updated_at 에 대해서 자동으로 날짜를 설정하고, 갱신하는 작업을 수행하다. 이 중 created_at 컬럼은 사용하고, updated_at 컬럼은 사용하지 않을 경우에는…
Submitted 8 years ago in Eloquent
3995
0
0
URL과 쿼리스트링 구하기
http://example.com/test?foo=bar url() // http://example.com Request::getPathInfo() // /test Request::url() // http://example.com/test Request::fullurl() // http://example.com/test?foo=bar Request::getQueryString() // foo=bar
Submitted 8 years ago in Request and Input
3931
0
0
특정 라우팅은 HTTPS 만 가능하게 하기
특정 요청은 무조건 https로만 접근하게 하고자 할 때, http로 접속한 경우 https로 리다이렉트 하도록 하기 위해서 다음의 Middleware를 사용하면 된다. app/Http/Middleware/ForceHttps.php <?php namespace…
Submitted 8 years ago in Routing
3652
0
0
Lumen, Laravel 겸용 패키지 만들기
패키지를 개발할 때, Laravel과 Lumen을 동시에 지원하고자 한다면, config 관련해서는 다음의 방법을 사용할 수 있다. class SampleServiceProvider extends ServiceProvider { /** * Bootstrap the application events. * *…
Submitted 8 years ago in Lumen
4504
0
0
최적화 명령어들
최적화 명령어들 php artisan optimize php artisan config:cache php artisan route:cache 최적화 명령어로 생성된 캐시 삭제 명령어들 php artisan clear-compiled php artisan config:clear php artisan route:clear php artisan view:clear…
Submitted 8 years ago in Performance
3800
0
0
Vagrant, Vaprobash를 이용해서 Laravel 개발용 VM 만들기
Vaprobash는 Implementing Laravel의 저자 Chris Fidao이 만든 Vagrant Provisioning 도구이다. Apache, MySQL, PHP 등 각종 소프트웨어 대한 설치 스크립트의 모임이라고 보면 될 것 같다. VM 만들기 Composer 설치 $ curl…
Submitted 10 years ago in Configuration
2266
0
0
로그 메시지에 회원 아이디, ip 등 원하는 정보 추가하기
사이트를 운영하면서 오류가 발생을 하면 로그 정보에 많이 의존하게 된다. 하지만 Laravel이 기본으로 제공하는 로그 메시지로는 디버깅이 많이 불편하다. 그래서 로그 메시지에 원하는…
Submitted 10 years ago in Debugging
3174
0
0
국가 셀렉트 박스 매크로
국가 셀렉트 박스를 표시하기 위한 Form::macro
Submitted 10 years ago in Template, Helper
4376
0
0
날짜를 몇시간 전, 며칠 전 형태로 표시하기
페이스북이나 트위터 등의 타임라인에서는 보통 등록시간을 몇분 전, 며칠 전 같은 형태로 표시를 한다. Laravel에서는 Carbon 클래스를 사용하면 쉽게 구현할 수 있다.
Submitted 10 years ago in Helper
3907
0
0
oh my zsh에서 artisan 자동완성 사용하기
oh my zsh을 사용한다면 laravel4 플러그인을 설치해서 artisan 명령 실행시 tab키를 눌러서 자동완성 기능을 사용할 수 있다.
Submitted 10 years ago in Packages
3174
0
0
bootstrap 3 Form macro
bootstrap 3 폼 마크업을 도와주는 폼 매크로. 매크로는 app/start/global.php 아래부분에 추가를 하면 되고, 따로 파일로 빼서 추가해도 된다. 출처: http://laravelsnippets.com/snippets/bootstrap-3-form-macros
Submitted 10 years ago in Views, Form
2337
0
0
Laravel 프레임웍 없이 Eloquent 사용하기
Laravel 프레임을 사용하지 않더라도 Eloquent ORM을 사용할 수가 있다. eloquent 설치 $ composer require illuminate/database database.php 파일 생성 <?php require 'vendor/autoload.php'; use Illuminate\Database\Capsule\Manager as…
Submitted 10 years ago in Eloquent
3839
0
0
Laravel-4-Generator Cheat Sheet
Laravel 필수 패키지 중 하나인 Laravel-4-Generators의 Cheat Sheet $ php artisan generate:migration create_posts_table $ php artisan generate:migration create_posts_table --fields=&quot;title:string, body:text&rdquo; $ php artisan…
Submitted 10 years ago in Packages
2346
0
1
모든 폼에 대해서 CSRF 자동으로 막기
route.php에 다음의 필터를 추가하면 POST, PUT, DELETE 요청에 대해서 csrf 필터링이 동작한다. Form 클래스를 사용하면 자동으로 _token이라는 히든 입력이 추가되지만, Form 클래스를 사용하지 않는…
Submitted 10 years ago in Routing, Form, Security
2760
0
0
서비스 환경에서 artisan 실행시 실행 여부 묻기
서비스 환경에서 migrate:refresh 같은 artisan 명령어를 실행시켜 의도치 않게 DB를 날릴 수도 있다. 이를 보완하기 위해서 다음의 코드를 artisan 앞에 추가하면 서비스 환경에서는 artisan 명령 실행시…
Submitted 10 years ago in Configuration
2749
0
0
email 보내기
Laravel 4의 Mail 패키지를 이용해서 이메일 발송하기
Submitted 10 years ago in Mail
3123
0
0
생성 날짜별 정렬 쿼리 축약형 메소드
Illumiate\Database\Query\Builder 객체에는 생성 날짜별 정렬에 대한 축약 메소드를 제공한다. <?php MyModel::where('user_id', $userId)->orderBy('created_at', 'desc')->first(); // 동일한 코드 MyModel::where('user_id',…
Submitted 10 years ago in Eloquent, Queries
2854
0
0
긴 라우팅 파일 분리하기
라우팅이 많아지면 라우팅 파일이 엄청 길어져서 관리하기가 불편하다. 다음의 팁을 사용하여 URL 별로의 라우팅 파일을 둘 수가 있다.
Submitted 10 years ago in Routing
3049
0
0
jQuery ajax 호출시 CSRF 막기
jQuery ajax 호출시 CSRF 막기 master layout 파일 수정 <meta name="_token" content="{{ csrf_token() }}" /> . . . <script> /* </body> 태그 전에 */ $(function() { $.ajaxSetup({ headers: { 'X-CSRF-Token':…
Submitted 10 years ago in Form, Request and Input, Security
4990
0
0
DB의 모든 쿼리를 화면에 출력하기
Eloquent ORM이 어떤 마술을 부리는지 알고 싶을 때가 많다. Laravel의 이벤트 리스너를 사용하면 간단하게 어떤 쿼리가 생성되서 실행되는지 볼 수가 있습니다. // Display all SQL executed in Eloquent…
Submitted 10 years ago in Eloquent, Queries, Debugging
2960
0
0
php 내장 웹서버 실행하기
php는 5.4부터 웹서버를 내장하고 있다. 개발이나 간단한 테스트시 이 웹서버를 사용하면 편하다. Laravel에서는 php artisan serve을 이용해서 내장 웹서버를 실행할 수 있다. $ php artisan serve Laravel…
Submitted 10 years ago in Debugging, Testing
5738
0
0
asset 버전 관리하기
css나 javascript등은 페이지 로드 속도를 개선하기 위해서 보통 웹서버 설정시 만료 날짜를 길게 잡는다. 참고 : Add a far future Expires header to your components. css, javascript 파일이 수정됐을 때는,…
Submitted 10 years ago in Cache, Helper
3195
0
0
laravel 5.4 새 기능
동영상 Laracast 무료 시리즈 - What's New in Laravel 5.4 Laracast 무료 시리즈 - Laravel 5.4 From Scratch Laravel 5.4 New Features - Part 1: All the Small Changes Overview Part 2: Laravel Mix [Laravel 5.4 New Features] articles What’s New…
Submitted 7 years ago in Features
4705
0
0
5.4
Raw Queries DB::select, DB::statement
DB::select DB::select는 Eloquent나 쿼리 빌더로 해결하기 어려운 복잡한 쿼리를 수행해서 데이타를 선택할 때 사용하면 좋다. 다음의 코드를 생각해 보자. $someVariable = Input::get("some_variable"); $results =…
Submitted 10 years ago in Eloquent, Queries
2766
0
0
가장 짧은 php swap 코드
가장 짧은 php swap 코드
Submitted 10 years ago in Helper
3223
0
0
redis, logstash, elasticsearch, kibana를 이용해서 실시간 로그 모니터링 하기
웹서비스를 운영하다 보면 장애 탐지나 버그 수정 등 많은 경우 로그 정보에 의존해서 문제를 해결하게 된다. redis, logstash, elasticsearch, kibana의 조합을 사용하면 Laravel에서 남기는 로그의…
Submitted 10 years ago in Configuration, Debugging
6293
0
0
Eloquent 쿼리, 파일에 로그 남기기
Before you start with this create a file in your logs folder (eg : 'query.log') and grant laravel write access to it. Place the snippet in your '/app/start/local.php' file. (or routes.php or anywhere...) Access artisan from your console and type this $…
Submitted 10 years ago in Eloquent, Debugging
2758
0
0
다중 환경 설정하기
개발, 스테이징, 서비스 등 Laravel 동작 환경을 여러 개로 나누고 각각의 환경에 맞게 설정을 따로 가져가는 방법을 알아보자. 1. 환경변수를 이용하는 방법 bootstrap/start.php 파일에서 환경…
Submitted 10 years ago in Configuration
3733
0
0
DB 테이블에 기본 timestamps 컬럼 외에 다른 날짜타입 컬럼 추가하기
블로그 글을 담고 있는 posts 테이블이 있고, 다음과 같이 컬럼이 구성되어 있다. Schema::create('posts', function($table) { $table->increments('id'); $table->string('title'); $table->timestamps(); // 마지막 수정일…
Submitted 10 years ago in Eloquent
3338
0
0
composer.json의 require, reduire-dev의 차이점
composer.json에 패키지 의존성을 정의할 때 require와 reuire-dev를 사용한다. { ... "require": { "laravel/framework": "4.1.*" }, "require-dev" : { "mockery/mockery" : "dev-master", "phpunit/phpunit" : "3.7.*", "codeception/aspect-mock" :…
Submitted 10 years ago in Packages, Composer
4832
0
2
Eloquent의 Accessors와 Mutators
DB에서 데이터를 읽을 때, 혹은 저장할 때 규칙을 정해서 값을 변환하고 싶을 때가 있다. 날짜를 읽을 때 YYYY-MM-DD의 문자열로 바꾼다든지, 비밀번호를 저장할 때 해시코드로 저장하든지 등을…
Submitted 10 years ago in Eloquent
2542
0
0
blade 템플릿의 `{{`와 `{{{`의 차이점
블레이드 템플릿에서는 화면 출력을 위해서 이중괄호({{..}})와 삼중괄호({{{..}}})를 사용할 수가 있다. 이 두 가지의 차이점은 무엇인가? 다음의 내용을 갖는 블레이드 템플릿 파일이 있다고…
Submitted 10 years ago in Views, Template
3035
0
0
모델의 날짜 출력 포맷 정하기
Eloquent의 Accessor를 사용해서 날짜의 출력 포맷을 정할 수 있다. class Post extends Eloquent { public function getUpdatedAtAttribute($value) { return Carbon::parse($value)->format('d/m/Y H:i:s'); } public function…
Submitted 10 years ago in Views, Eloquent
3277
0
0