1.마이그레이션 파일을 작성한다.

1
php artisan  make:migration drop_posts_tag_id_colum
cs


2. 스키마를 작성한다. posts = 테이블명, tag_id = 삭제할 컬럼

1
2
3
4
5
6
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->dropColumn('tag_id');
        });
    }
cs


3. 마이그레이션실행한다.

php artisan migrate


컬럼이 삭제된것을 확인 할 수 있다.



리소스에는 다양한 필드가 있지만 유효성 검사라는 중요한 기능이 없음.

잘못된 입력을 방지하기 위해 필요한 유효성 검사 규칙을 리소스에 추가한다.


Posts에 유효성 검사를 넣어보자


1. Nova/Post.php 을 열고 소스를 작성한다.

유효성검사를 넣을곳 해당fields정의 뒤에 rules([규칙]); 을 넣어주면 된다.


입력을 하지 않게 되면 아래와 같이 메시지가 뜬다.


규칙참고 사이트

https://laravel.com/docs/6.x/validation#available-validation-rules


필수 입력 항목 설정 : required


오늘 이후의 날짜를 입력 : after_or_equal:today


publish_at 날짜 이후 입력 : after_or_equal:publish_at

'라라벨 > NOVA' 카테고리의 다른 글

수색(Searching)  (0) 2020.01.02
자원(resource)의 권한(Authorization) policy(정책)  (0) 2020.01.01
자원의(resource) 관계(Relationships)  (0) 2020.01.01
자원(resource)의 분야 field  (0) 2019.12.31
자원(resource)의 정의  (0) 2019.12.31

리소스 관계를 관리하는 방법

BelongsTo : 나는 속한다.

HasMany : 많은 관계를 맺는다.

BelongsToMany: 나는 여러개에 소속된다.


1. app/Post.php 소스에 들어가서 관계를 설정해준다.

1
2
3
4
5
    public function user()
    {
        // 나는 유저에게 속한다.
        return $this->belongsTo(User::class);
    }
cs


반대로 app/User.php 에게도 관계를 설정해준다.

1
2
3
4
5
    public function posts()
    {
        //나는 여러개의 post를 가지고 있습니다. 여기서 나는 user이다.
        $this->hasMany(Post::class);
    }
cs


2. app/Nova/Post.php  fields메서드로 가서 소스를 삽입해준다.


BelongsTo::make('User')


상단에 꼭 넣어주자(비주얼스튜디오코드에서 ctrl+speace 자동 임포트 된다.

1
use Laravel\Nova\Fields\BelongsTo;
cs


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
    public function fields(Request $request)
    {
        return [
            ID::make()->sortable(),
 
            Text::make('Title')->sortable(),
 
            Trix::make('Body')->sortable(),
 
            DateTime::make('Publish At')->hideFromIndex(),
 
            DateTime::make('Publish Until')->hideFromIndex(),
 
            Boolean::make('Is Published'),
 
            Select::make('Category')->options([
 
                'tutorials' => 'Tutorials',
                'news' => 'News'
 
            ])->hideWhenUpdating(),
 
            BelongsTo::make('User')
 
        ];
    }
cs


목록에 user필드가 추가되었다.


그냥입력하면 에러가 뜰것이다. 컬럼추가 마이그레이션파을을 새로 만들어주자

1
php artisan make:migration --table=posts add_more2_post_columns
cs


스키마추가

1
2
3
4
5
6
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->unsignedInteger('user_id');
        });
    }
cs


마이그레이션실행

1
php artisan migrate
cs


db테이블을 확인해보면 user_id 컬럼이 생성되었다.


수정을 눌러서 user선택후 업데이트를 하면 적용이 된다.


User을 name값으로 변경하려고 하면 Nova/User.php

1
public static $title = 'name';
cs


값을 변경해주자 email or name


3. User 목록에서 유저를 클릭하면 유저가 작성한 Posts를 구현해보자


app/Nova/User.php 에서 HasMany::make('Posts') 추가하자

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
    public function fields(Request $request)
    {
        return [
            ID::make()->sortable(),
 
            Gravatar::make(),
 
            Text::make('Name')
                ->sortable()
                ->rules('required', 'max:255'),
 
            Text::make('Email')
                ->sortable()
                ->rules('required', 'email', 'max:254')
                ->creationRules('unique:users,email')
                ->updateRules('unique:users,email,{{resourceId}}'),
 
            Password::make('Password')
                ->onlyOnForms()
                ->creationRules('required', 'string', 'min:8')
                ->updateRules('nullable', 'string', 'min:8'),
 
            HasMany::make('Posts')
        ];
    }
cs


app/User.php

return(반환) 을 추가해주자


유저를 클릭하면 유저가 작성해놓은 글이 보일 것이다.


4. Tag resource를 만들어보자(마이그레이션,모델 파일 필수)

1
php artisan nova:resource Tag
cs


Nova디렉토리에 Tag.php파일이 생성되었다.


Tags마이그레이션 파일을 만들어주자

1
php artisan make:migration create_tags_table --create=tags
cs


스키마

1
2
3
4
5
6
7
8
    public function up()
    {
        Schema::create('tags', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('tag');
            $table->timestamps();
        });
    }
cs


모델을 만들어주자(모델은 단수이다)

1
php artisan make:model Tag
cs


Tag라는 리소스가 등록되었다.


Nova/Tag.php 파일을 수정해주자

1
public static $title = 'tag';
cs


1
2
3
    public static $search = [
        'id','tag'
    ];
cs


필드를 추가하자

1
2
3
4
5
6
7
8
    public function fields(Request $request)
    {
        return [
            ID::make()->sortable(),
 
            Text::make('Tag')
        ];
    }
cs


Tag를 추가해보자


5. app/Post.php 에 관계를 설정하자.

1
2
3
4
5
    public function tags()
    {
        //나는 태그에 속한다.
        return $this->belongsToMany(Tag::class);
    }
cs


app/Tag.php 에 관계를 설정하자.

1
2
3
4
    public function posts()
    {
        return $this->belongsToMany(Post::class);
    }
cs


Nova/Post.php 에 필드를 추가하자

1
 BelongsToMany::make('Tags')
cs


여기서 엄청 해맸다 이후 되지가 않았기 때문이다


SQLSTATE[42s02]: Base table or view not found: 1146 Table ‘laravel nova.post_tag’ doesn’t exist(SQL:select `tags`.*,`post_id` as `pivot_post_id`,`post_tag`.`tag_id` as `pivot_tag_id` from `tags` inner join `post_tag` on `tags`.`id` = `post_tag`.`tag_id` where `post_tag`.`post_id` = 6 order by `tags`.`id` desc limit 6 offset(0)


해결방법>

테이블을 만들어준다. post_tag

1
php artisan make:migration create_post_tag_table
cs


테이블스키마

1
2
3
4
5
6
7
8
9
    public function up()
    {
        Schema::create('post_tag', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('post_id')->unsigned();
            $table->integer('tag_id')->unsigned();
            $table->timestamps();
        });
    }
cs


테이블이 생성되었으니 다시 실행해보자


우와~~ 된다.~~~ 8시간 까먹었다.  관계는 잘 이해가 가지 않는다. 연습을 많이 해봐야겠다.


6. Nova/Tag.php 파일에서 다음과 같이 소스를 field를 추가한다.

1
2
3
4
5
6
7
8
9
10
    public function fields(Request $request)
    {
        return [
            ID::make()->sortable(),
 
            Text::make('Tag'),
 
            BelongsToMany::make('Posts')
        ];
    }
cs


해당태그 디테일 클릭시 해당Posts 관계를 보여준다.


'라라벨 > NOVA' 카테고리의 다른 글

자원(resource)의 권한(Authorization) policy(정책)  (0) 2020.01.01
자원(resource)의 검증(vaildation)  (0) 2020.01.01
자원(resource)의 분야 field  (0) 2019.12.31
자원(resource)의 정의  (0) 2019.12.31
nova설치하기  (0) 2019.12.31

1. 마이그레이션에서 posts 의 컬럼을 추가하는 명령어를 입력하자

1
php artisan make:migration --table=posts add_more_post_columns
cs



2. 마이그레이션을 작성한다.

1
2
3
4
5
6
7
8
9
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->datetime('publish_at')->nullable();
            $table->datetime('publish_until')->nullable();
            $table->boolean('is_published')->default(false);
            $table->string('category')->nullable();
        });
    }
cs


마이그레이션을 실행해준다.


3. Nova/Post.php 파일을 열어 소스를 수정해준다.


필드타입보기> https://nova.laravel.com/docs/2.0/resources/fields.html#field-types


아래와 같이 필드를 추가해보자

sortable() = 목록에서 정렬을 할 수 있게 해준다.




대시보드로 가서 새로고침하면 아래와 같이 변경된 것을 확인할 수 있다.




Post.php 파일에서 정의 해주자

1
2
3
4
5
6
    protected $casts = [
 
        'publish_at' => 'datetime',
        'publish_until' => 'datetime'
 
    ];
cs



4. Post.php 파일에 다시 필드를 추가 해준다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
    public function fields(Request $request)
    {
        return [
            ID::make()->sortable(),
 
            Text::make('Title')->sortable(),
 
            Trix::make('Body')->sortable(),
 
            DateTime::make('Publish At')->sortable(), //public_at
 
            DateTime::make('Publish Until')->sortable(), //public_at
 
            Boolean::make('Is Published'),
 
 
        ];
    }
cs


필드가 추가 되었다.


Boolean 체크박스가 적용되었다.


5. 이제 카테고리필드를 만들어보자

1
2
3
4
5
6
            Select::make('Category')->options([
 
                'tutorials' => 'Tutorials',
                'news' => 'News'
 
            ])
cs



5.1 카테고리 업데이트를 못하게 막으려면 hideWhenUpdating() 메서드를 넣어주자

1
2
3
4
5
6
            Select::make('Category')->options([
 
                'tutorials' => 'Tutorials',
                'news' => 'News'
 
            ])->hideWhenUpdating()
cs


업데이트시 카테고리가 보이지 않게 되었다. 하지만 글쓰기를 하면 정상적으로 보여진다.


필드숨기는 기능 메뉴얼:

https://nova.laravel.com/docs/2.0/resources/fields.html#showing-hiding-fields



6. 필드가 너무 많아서 목록에서 숨기고 싶은 경우


필드 뒤에 hideFromIndex() 메서드를 추가한다.

1
2
3
            DateTime::make('Publish At')->hideFromIndex(), 
 
            DateTime::make('Publish Until')->hideFromIndex(), 
cs


이제 필드에서 보이지 않게 되었다.


7. 6번의 반대로 수정에서 보이지 않게 하려면 onlyOnIndex() 메서드를 넣어주면 됨

1
Boolean::make('Is Published')->onlyOnIndex(),
cs


블리언 체크하는 컬럼이 사라졌다.


'라라벨 > NOVA' 카테고리의 다른 글

자원(resource)의 권한(Authorization) policy(정책)  (0) 2020.01.01
자원(resource)의 검증(vaildation)  (0) 2020.01.01
자원의(resource) 관계(Relationships)  (0) 2020.01.01
자원(resource)의 정의  (0) 2019.12.31
nova설치하기  (0) 2019.12.31

1. user을 만드는 부분이다. (등록,수정,삭제를 할 수 있다.)


app/Nova/User.php 이렇게 연결 되어있나보다.



2. 마이그레이션과 모델 파일을 만들어주자 여기서는 각각 만들겠다.


posts 마이그레이션 파일을 하나 만들어주자

1
php artisan make:migration create_posts_table --create=posts
cs



1
2
3
4
5
6
7
8
9
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });
    }
cs



1
php artisan make:model Post
cs



마이그레이션 해준다. php artisan migrate



3. 터미널에서 php artisan nova:resource Post 입력하자.


Nova/Post.php 파일이 생성되었다.


Posts 라는 메뉴가 생성되었다.


app/Nova/Post.php 에서 소스를 수정한다.

1
public static $title = 'title';
cs


1
2
3
   public static $search = [
        'id', 'title', 'body'
    ];
cs


1
2
3
4
5
6
7
8
9
10
    public function fields(Request $request)
    {
        return [
            ID::make()->sortable(),
 
            Text::make('Title')->sortable(),
 
            Trix::make('Body')->sortable(),
        ];
    }
cs


상단에 아래와 같이 넣어주길...

1
2
3
4
use Illuminate\Http\Request;
use Laravel\Nova\Fields\ID;
use Laravel\Nova\Fields\Text;
use Laravel\Nova\Fields\Trix;
cs


Fields 명을 변경하고 싶은경우 

1
 Number::make('사용자정의 이름','테이블명'),
cs



4. 아래와 같이 나오면 된다.


글을 작성하면 잘 입력된다.



5. 만약 사이드바에 보여지게 하지 않을려면 

해당 Nova/Post.php 파일에서 아래와 같이 소스를 넣으면 된다.


1
public static $displayInNavigation = false;
cs



아래와 같이 사이드에서 자원메뉴가 없어졌다.


메뉴를 그룹으로 만들 수 도 있음.

1
public static $group = 'Admin';
cs


페이지 매김 사용자 정의

1
 public static $perPageOptions = [10, 100, 150];
cs


1. nova 결제하기

https://nova.laravel.com/



2. 노바소스프로그램 다운로드 받기



3. 다운로드받은 파일을 압축을 풀고 라라벨 해당 프로젝트안에 넣어준다.



4. .gitignore 파일을 열어주고 nova를 추가한다. 깃 업로드시 해당 폴더를 업로드하지 않겠다는 것이다.


5. composer.json 파일을 열어서 아래와 같이 추가한다. 2군데


1
2
3
4
5
6
    "repositories":[
        {
            "type": "path",
            "url": "./nova"
        }
],
cs



5-1. 아래도 사진과 같이 추가한다.

1
"laravel/nova":"*"
cs



6. 터미널에서 composer update  입력

오류시 다음과 같이 실행

https://laracasts.com/discuss/channels/nova/installing-nova-20-on-laravel-58-is-throwing-errors

1
sudo apt-get install php7.2-bcmath
cs



7. 터미널에서 php artisan nova:install 입력 


8. .env 파일을 열어서 데이터베이스 계정을 입력해준다.


9. php artisan migrate 마이그레이션을 실행한다.


10. 호스트/nova/login 을 입력한다.


11. nova 유저를 생성한다.

터미널에서 php artisan nova:user 입력한다. 


12. 해당 유저로 접속을 한다. 그럼 아래와 같은 대시보드가 보일 것이다.


1
 composer create-project laravel/laravel myapp --prefer-dist 6.0
cs



설치 후 composeer.json 파일을 열어보면 버전을 확인 할 수 있다.


원본글 : https://zetawiki.com/wiki/MySQL_%EC%9B%90%EA%B2%A9_%EC%A0%91%EC%86%8D_%ED%97%88%EC%9A%A9


mysql -uroot -p


use mysql;


SELECT Host,User,plugin,authentication_string FROM mysql.user;


GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'password';


FLUSH PRIVILEGES;


netstat -ntlp | grep mysqld    (127.0.0.1:3306) 이렇게 되있어서 로컬 호스트에서만 접속가능


vi /etc/mysql/my.cnf

아래와 같이 설정해준다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#
# If the same option is defined multiple times, the last one will apply.
#
# One can use all long options that the program supports.
# Run program with --help to get a list of available options and with
# --print-defaults to see which it would actually understand and use.
 
#
# This group is read both both by the client and the server
# use it for options that affect everything
 
[client-server]
 
 
 
 
# Import all .cnf files from configuration directory
!includedir /etc/mysql/conf.d/
!includedir /etc/mysql/mariadb.conf.d/
[mysqld]
bind-address=0.0.0.0
 
 
cs


service mysql restart


netstat -ntlp | grep mysqld  (0 0.0.0.0:3306) 이렇게 바뀌어서 외부접속이 허용가능하다.


접속을 해보면 정상적으로 될 것이다.


이렇게 해도 안된다.


/etc/mysql/mariadb.conf.d


이동하여
 vi 50-server.cnf


수정해준다.

[재시작]
service mysql restart

[네트워크확인]
netstat -ntlp | grep mysqld



외부에서 접속해본다. 




'Ubuntu' 카테고리의 다른 글

composer install 오류 php7.2  (0) 2020.04.04
git 설치 및 설정  (0) 2020.04.04
marialdb database 생성 및 권한주기  (0) 2019.12.30
php7.2 curl 설치  (0) 2019.12.30
composer 설치하기  (0) 2019.12.30

+ Recent posts