댓글 많이 달린 tricks

리소스 네이밍 규칙
네이밍은 규칙 정하기 나름이지만 다음과 같이 정하면 어떨까 한다. Model만 단수형을 사용하고, DB Table, Controller, Route, View 등은 복수형을 사용한다. 예) Task Model : Task DB Table : tasks Controller :…
Submitted 10 years ago in Configuration
3664
0
0
helper 함수는 어디에?
자주 사용하는 간단한 유틸성 함수는 클래스의 정적 메서드나 퍼사드를 만드는 것 보다 함수로 만들어서 하나의 php 파일에 두고 쓰는 게 더 좋아 보인다. app/libraries 폴더를 만들고 여기에…
Submitted 10 years ago in Configuration, Composer, Helper
2494
0
1
다운타임없이 Laravel 4.1.26으로 업그레이드 하기
인증시 사용되는 remember me 쿠키에 보안 문제가 생겨서 Larvel 4.1.26이 릴리즈 됐습니다. Laravel 4.1.26을 업그레이드를 하려면 패키지는 물론 User.php와 users DB 테이블을 변경해야 한다. 다음의…
Submitted 10 years ago in Configuration
3352
0
1
1픽셀 투명이미지 출력하기
별도의 이미지 파일을 두지 않고 (IO를 줄이기 위해서) 가로, 세로 1 픽셀짜리 투명 이미지를 출력하는 방법 $img =…
Submitted 10 years ago in Performance
3816
0
0
모든 POST 요청에 대해 컨트톨러에서 CSRF 막기
POST 요청에 대해 CSRF를 막는 방법 중 컨트롤러에 기반을 둔 방식이다.
Submitted 10 years ago in Request and Input, Security
2928
0
0
제목이 변경돼도 이전 링크로 블로그 글 찾아갈 수 있도록 URL slug 만들기
Laravel로 블로그 시스템을 만들었다고 하자. 보통 블로그 글 URL은 Str::slug 메서드를 사용해서 만들게 된다. $url = Str::slug('My First Blog Post!'); // my-first-blog-post 슬러그(Slug)는 핵심 키워드 만을…
Submitted 10 years ago in Routing
2692
0
0
gmail 계정을 이용해서 메일 발송하기
메일 발송시 gmail을 사용해서 보내기 위해서 app/config/mail.php을 다음의 내용으로 수정해야 한다.
Submitted 10 years ago in Mail
2870
0
0
라우팅 패턴
라우팅 패턴 정리
Submitted 10 years ago in Routing
3275
0
0
Laravel 5.0에서 Blade 변경 사항
Laravel 4.x에서 {{와 {{{는 다르게 동작한다. {{{는 출력시 이스케이프가 행해지고, {{는 그대로 출력된다. 보다 자세한 내용은 blade 템플릿의 {{와 {{{의 차이점을 참고하면 된다. Laravel 5.0에서는 {{,…
Submitted 9 years ago in Views, Template
2697
0
0
CORS middleware 간단설정
Ajax활용시 CORS설정을 해주지 않으면 브라우정에서 다른 도메인 주소로 Ajax요청을 하는것이 불가능하게 되어있다. 브라우저 정책상의 문제로 다른 매체로 링크활용시에는 아무런 문제없다.…
Submitted 9 years ago in Routing
2617
0
1
5.0
timestamps 컬럼명 지정하기
timestamps를 사용하는 경우 (default) created_at, updated_at, deleted_at 컬럼명이 기본인데, 다음의 방법으로 이를 변경할 수 있다. 방법 1 User extends Eloquent{ const CREATED_AT = 'registered_at'; const UPDATED_AT =…
Submitted 10 years ago in Eloquent
3376
0
0
composer update 또는 install 오류 발생했을 때 원인 파악하기
composer update 나 composer install 수행시 오류가 발생했다면 -vvv 옵션으로 오류 발생 지점 및 원인을 좀더 자세하게 볼 수 있다. composer에서 발생한 오류일 수도 있고, php artisan에서 발생한 오류일…
Submitted 10 years ago in Composer
4529
0
1
`Validation` 사용시 어떤 규칙에 위반됐는지 확인하는 방법
Validation 사용시 어떤 규칙에 맞지 않아서 유효성 검사를 통과하지 못했는지 체크하는 방법 $rules = array( 'file' => 'required|max:1000' ); $validator = Validator::make(Input::all(), $rules); if ($validator->fails())…
Submitted 9 years ago in Request and Input
2179
0
0
폼 검증시 강제로 오류 추가하기
$validator->getMessageBag()->add('email', 'Email wrong');
Submitted 9 years ago in Request and Input
2177
0
0
Eager Loading 체이닝
User, Phone, Post 세 개의 모델이 있고, 다음의 관계를 갖는다고 가정하자. class User extends Eloquent { public function phone() { return $this->hasOne('Phone'); } publif function posts() { return $this->hasMany('Post'); } }…
Submitted 9 years ago in Eloquent
2988
0
0
Laravel 5에서 DB 쿼리 로그 남기기
Laravel 5에서는 쿼리 로그가 기본적으로 비활성화 되어 있어서, 이전 버전처럼 바로 DB::getQueryLog()를 하면 빈 배열이 반환된다. 쿼리로그 활성화 DB::enableQueryLog(); 쿼리로그 얻기 $queries =…
Submitted 8 years ago in Eloquent, Queries
7338
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
2366
0
0
뷰없이 이메일 발송하기
결론을 먼저 얘기하면 Laravel에서 제공하는 기본 Mail 패키지를 사용하는 한 view 페이지 없이 메일을 발송할 수 없다. 하지만 다음의 꼼수를 사용하면 비슷한 효과를 낼 수 있다.…
Submitted 9 years ago in Mail
2686
0
0
세션 사용하지 않기
세션이 필요가 없는 경우, 세션의 사용은 큰 자원의 낭비이다. API 서비스 등이 대표적인 예일 것 같다. 다음 필터를 사용하면 특정 라우팅에 대해서 세션을 사용하지 않도록 할 수 있다.…
Submitted 10 years ago in Session, Performance
2529
0
0
Homestead를 이용해서 Laravel 개발 환경 만들기
Laravel 개발 환경을 구축하기 위한 가장 쉬운 방법을 이제 Laravel에서 제공을 한다. 2014 Laracon에서 Taylor Otwell이 소개한 Homestead가 그것이다. Laravel 4.2부터는 local 환경 설정으로 homestead를 기본으로…
Submitted 10 years ago in Configuration
6899
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
4401
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
2608
0
0
Blade에서 New LIne을 <br>로 바꾸기
사용자가 입력한 내용을 그대로 출력을 하면 엔터키를 입력했더라도 그대로 붙어서 출력이 된다. 이를 보완하기 위해서는 nl2br함수를 사용해서 <br>태그로 변환을 하면 되는데, blade에서는…
Submitted 9 years ago in Views, Security
2353
0
0
개발 환경과 서비스 환경 쉽게 바꾸기
Laravel 5에서 환경 설정 방법이 변경되서 개발 환경과 서비스 환경을 관리하기가 전 버전보다 귀찮은 것 같다. 그래서, 환경 설정 파일을 변경하는 스크립트를 만들어서 사용하면 좀 편하지…
Submitted 8 years ago in Configuration
5000
0
0
FreeTDS를 이용해서 MS SQL Server 연결시 날짜 포맷 지정하기
linux 머신에서 Laravel 프레임웍을 이용해서 MS SQL Server에 접속할 때는 FreeTDS 라이브러리가 사용된다. 비록 이 환경이 바람직하다고 생각하지는 않지만, MS SQL Server를 사용하는 한 이 구성을…
Submitted 10 years ago in Configuration
3052
0
0
로그인한 후 리다이렉트 되는 URL 변경하기
Laravel은 로그인이 성공한 뒤 /home 으로 라다이렉트한다. 이를 다른 URL로 변경하려면 AuthController에 $redirectPath 속성을 추가해서 지정하면 된다. App\Http\Controllers\Auth\AuthController namespace…
Submitted 8 years ago in Security
4380
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
3662
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
6207
0
0
console 로그와 웹 로그 분리하기
로그 설정을 daily로 하고, artisan command 등의 console 명령을 스케쥴링을 통하여 수행하는 경우 console 계정과 웹 계정의 차이로 인해 다음의 문제가 발생하는 경우가 있다. Failed to open stream:…
Submitted 8 years ago in Configuration, Debugging
6238
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
5533
0
0
PasswordBroker 오버라이딩하기
비밀번호 리셋에 관련된 로직은 Illuminate\Auth\Passwords\PasswordBroker 클래스에서 수행이 되는데, 이 로직을 변경하고자 한다면 다음의 방법을 사용하면 된다. CustomPassowordBroker 생성…
Submitted 8 years ago in Security
3582
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
4120
0
0
updated_at 컬럼 사용하지 않기
Laravel Eloquent는 timestamp 컬럼인 created_at, updated_at 에 대해서 자동으로 날짜를 설정하고, 갱신하는 작업을 수행하다. 이 중 created_at 컬럼은 사용하고, updated_at 컬럼은 사용하지 않을 경우에는…
Submitted 8 years ago in Eloquent
4138
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
4039
0
0
특정 라우팅은 HTTPS 만 가능하게 하기
특정 요청은 무조건 https로만 접근하게 하고자 할 때, http로 접속한 경우 https로 리다이렉트 하도록 하기 위해서 다음의 Middleware를 사용하면 된다. app/Http/Middleware/ForceHttps.php <?php namespace…
Submitted 8 years ago in Routing
3789
0
0
Lumen, Laravel 겸용 패키지 만들기
패키지를 개발할 때, Laravel과 Lumen을 동시에 지원하고자 한다면, config 관련해서는 다음의 방법을 사용할 수 있다. class SampleServiceProvider extends ServiceProvider { /** * Bootstrap the application events. * *…
Submitted 8 years ago in Lumen
4539
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
3938
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
2270
0
0
로그 메시지에 회원 아이디, ip 등 원하는 정보 추가하기
사이트를 운영하면서 오류가 발생을 하면 로그 정보에 많이 의존하게 된다. 하지만 Laravel이 기본으로 제공하는 로그 메시지로는 디버깅이 많이 불편하다. 그래서 로그 메시지에 원하는…
Submitted 10 years ago in Debugging
3182
0
0
국가 셀렉트 박스 매크로
국가 셀렉트 박스를 표시하기 위한 Form::macro
Submitted 10 years ago in Template, Helper
4386
0
0
날짜를 몇시간 전, 며칠 전 형태로 표시하기
페이스북이나 트위터 등의 타임라인에서는 보통 등록시간을 몇분 전, 며칠 전 같은 형태로 표시를 한다. Laravel에서는 Carbon 클래스를 사용하면 쉽게 구현할 수 있다.
Submitted 10 years ago in Helper
3922
0
0
oh my zsh에서 artisan 자동완성 사용하기
oh my zsh을 사용한다면 laravel4 플러그인을 설치해서 artisan 명령 실행시 tab키를 눌러서 자동완성 기능을 사용할 수 있다.
Submitted 10 years ago in Packages
3181
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
2342
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
3848
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
2349
0
1
모든 폼에 대해서 CSRF 자동으로 막기
route.php에 다음의 필터를 추가하면 POST, PUT, DELETE 요청에 대해서 csrf 필터링이 동작한다. Form 클래스를 사용하면 자동으로 _token이라는 히든 입력이 추가되지만, Form 클래스를 사용하지 않는…
Submitted 10 years ago in Routing, Form, Security
2766
0
0
서비스 환경에서 artisan 실행시 실행 여부 묻기
서비스 환경에서 migrate:refresh 같은 artisan 명령어를 실행시켜 의도치 않게 DB를 날릴 수도 있다. 이를 보완하기 위해서 다음의 코드를 artisan 앞에 추가하면 서비스 환경에서는 artisan 명령 실행시…
Submitted 10 years ago in Configuration
2756
0
0
email 보내기
Laravel 4의 Mail 패키지를 이용해서 이메일 발송하기
Submitted 10 years ago in Mail
3131
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
2860
0
0
긴 라우팅 파일 분리하기
라우팅이 많아지면 라우팅 파일이 엄청 길어져서 관리하기가 불편하다. 다음의 팁을 사용하여 URL 별로의 라우팅 파일을 둘 수가 있다.
Submitted 10 years ago in Routing
3055
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
4999
0
0
DB의 모든 쿼리를 화면에 출력하기
Eloquent ORM이 어떤 마술을 부리는지 알고 싶을 때가 많다. Laravel의 이벤트 리스너를 사용하면 간단하게 어떤 쿼리가 생성되서 실행되는지 볼 수가 있습니다. // Display all SQL executed in Eloquent…
Submitted 10 years ago in Eloquent, Queries, Debugging
2964
0
0
php 내장 웹서버 실행하기
php는 5.4부터 웹서버를 내장하고 있다. 개발이나 간단한 테스트시 이 웹서버를 사용하면 편하다. Laravel에서는 php artisan serve을 이용해서 내장 웹서버를 실행할 수 있다. $ php artisan serve Laravel…
Submitted 10 years ago in Debugging, Testing
5751
0
0
asset 버전 관리하기
css나 javascript등은 페이지 로드 속도를 개선하기 위해서 보통 웹서버 설정시 만료 날짜를 길게 잡는다. 참고 : Add a far future Expires header to your components. css, javascript 파일이 수정됐을 때는,…
Submitted 10 years ago in Cache, Helper
3202
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
4748
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
2769
0
0
가장 짧은 php swap 코드
가장 짧은 php swap 코드
Submitted 10 years ago in Helper
3230
0
0
redis, logstash, elasticsearch, kibana를 이용해서 실시간 로그 모니터링 하기
웹서비스를 운영하다 보면 장애 탐지나 버그 수정 등 많은 경우 로그 정보에 의존해서 문제를 해결하게 된다. redis, logstash, elasticsearch, kibana의 조합을 사용하면 Laravel에서 남기는 로그의…
Submitted 10 years ago in Configuration, Debugging
6300
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
2761
0
0
다중 환경 설정하기
개발, 스테이징, 서비스 등 Laravel 동작 환경을 여러 개로 나누고 각각의 환경에 맞게 설정을 따로 가져가는 방법을 알아보자. 1. 환경변수를 이용하는 방법 bootstrap/start.php 파일에서 환경…
Submitted 10 years ago in Configuration
3737
0
0
DB 테이블에 기본 timestamps 컬럼 외에 다른 날짜타입 컬럼 추가하기
블로그 글을 담고 있는 posts 테이블이 있고, 다음과 같이 컬럼이 구성되어 있다. Schema::create('posts', function($table) { $table->increments('id'); $table->string('title'); $table->timestamps(); // 마지막 수정일…
Submitted 10 years ago in Eloquent
3347
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
4845
0
2
Eloquent의 Accessors와 Mutators
DB에서 데이터를 읽을 때, 혹은 저장할 때 규칙을 정해서 값을 변환하고 싶을 때가 있다. 날짜를 읽을 때 YYYY-MM-DD의 문자열로 바꾼다든지, 비밀번호를 저장할 때 해시코드로 저장하든지 등을…
Submitted 10 years ago in Eloquent
2547
0
0
blade 템플릿의 `{{`와 `{{{`의 차이점
블레이드 템플릿에서는 화면 출력을 위해서 이중괄호({{..}})와 삼중괄호({{{..}}})를 사용할 수가 있다. 이 두 가지의 차이점은 무엇인가? 다음의 내용을 갖는 블레이드 템플릿 파일이 있다고…
Submitted 10 years ago in Views, Template
3040
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
3286
0
0