레이블이 Laravel인 게시물을 표시합니다. 모든 게시물 표시
레이블이 Laravel인 게시물을 표시합니다. 모든 게시물 표시

2022년 6월 17일 금요일

Laravel에서 constant or global variable 정의 best practice

 namespace App\Constants;

abstract class KeyConst

{

    const KEY_1 = "TUWYC";

    const KEY_2 = "DeNda";

    const KEY_3 = "tkz0w";

    const KEY_4 = "kVZLp";

    const KEY_5 = "g0sKJ";

}


해당 경로에 class 생성.


controller에서 아래 처럼 사용


use App\Constants\KeyConst;

$env_result = KeyConst::KEY_1;


혹은


config/app.php 에 alias 추가 후

'aliases' => [

  //...

  'MyConst' => App\Constants\KeyConst::class,

 Save

Finally use them wherever you like (controllers or even blades) :


controllers or blades 에서 사용

MyConst::KEY_1;


상수 추가 후 composer dump-autoload 등으로 로드해줘야 함.

2021년 6월 21일 월요일

Top Laravel Eloquent Features You May Not Know.

 

1. Check if Model changed

2. Get original attributes

3. Get changed attributes

Note: Here you need to keep in mind that, you will only get changes back if you save it or sync the changes with syncChanges()

4. Custom deleted_at column

5. Save relationships and models

6. Reload fresh model

7. Reload existing model

8. Check if models are the same

9. Clone a model

10. Specify attributes in find() method

Finally…

2021년 2월 9일 화요일

Laravel 뷰 트리구조 참고

 views/

├── mail
│ └── ...
├── components
│ ├── post-card.blade.php
│ ├── user-card.blade.php
│ ├── password-input.blade.php
│ └── image-container.blade
└── web/
├── layout
│ ├── header
│ │ ├── links.blade.php
│ │ ├── css.blade.php
│ │ └── js.blade.php
│ ├── header.blade.php
│ ├── head.blade.php
│ └── footer.blade.php
├── sections
│ ├── static
│ │ ├── home.blade.php
│ │ ├── about.blade.php
│ │ ├── contact.blade.php
│ │ └── layout.blade.php
│ ├── profile
│ │ ├── show.blade.php
│ │ ├── security.blade.php
│ │ ├── preferences.blade.php
│ │ └── layout.blade.php
│ ├── comment
│ │ ├── index.blade.php
│ │ ├── show.blade.php
│ │ ├── edit.blade.php
│ │ └── layout.blade.php
│ ├── user
│ │ ├── index.blade.php
│ │ ├── show.blade.php
│ │ ├── edit.blade.php
│ │ └── layout.blade.php
│ └── post
│ ├── subviews
│ │ ├── comment.blade.php
│ │ ├── author.blade.php
│ │ └── tags.blade.php
│ ├── index.blade.php
│ ├── show.blade.php
│ ├── edit.blade.php
│ └── layout.blade.php
└── layout.php

My take on organizing the Views directory is relatively simple. As you can see, in my Blog application I have multiple views: static views like the Home, a profile page for the authenticated user, and more views related to comments, users and posts.

Web Views

To separate Web Views from others, like Mails and other Vendor Views, I use the web directory . I consider this directory my starting point for anything that goes over the web, like a truthful HTML page.

This allows me to know where my web views are. I just use it to separate it from the others kinds of channels for the views. For example, if in the next year I need a way push HTML through AJAX, then I can use the ajax folder:

views/
├── mail
│ └── ...
├── components
│ └── ...
├── web
│ └── ...
└── ajax
└── ...

The “Master” Layout

There is a layout.blade.php file in the root folder of the web views, and this is the HTML skeleton for all others.

I usually define in this file the main sections of the whole HTML skeleton, like the <head>, along the <header>, <footer>, and the <main> parts. Depending on the complexity, I leverage the code directly to separate subviews in the layout directory.

While sections are almost mandatory to let views put content inside each part of the view, using stacks in these subviews is very useful to allow other views to inject CSS or JS they need:

// resources/views/web/layout/header.balde.php
<header>
<title>@yield('title')</title>
<link rel="stylesheet" type="text/css" href="/app.css">
<script src="/app.js"></script>
    @stack('head-css')
@stack('head-scripts')
</header>

I also put there CSS and JS from other frontend frameworks. This gives me a centralized way to handle and update these when I need to, instead of shoving everything into one view.

Most of the layouts I make end up like this, because I delegate each part of the application into its appropriate section.

Directory Sections

Creating a directory section is useful to categorize what the view is all about, and (hopefully) be the same as the route name.

// routes/web.php
Route::get('post/{post}', 'PostController@show')
->name('post.show');// PostController.php
public function show(Post $post)
{
return view('web.post.show', ['post' => $post]);
}

Trying to have everything using the same name makes locating and editing them a breeze since you don’t have to guess where your views are and where they are used.

My recommendation is to make directory sections for each model you have, and also for each part of your application where you need to put views that share the same concept: managing posts, show the authenticated user his information…

Section subviews

Everything that uses @include is a subview that mostly depends on the data passed to the parent view itself, so I push them inside it’s own directory to avoid polluting the big views.

These subviews are not meant to be reusable, but can be if another view can call them without further modification. If I need subviews shareable between directory sections, then I would remake them into components.

Doing subviews is a good way to lean the view from too much code. Consider the post.edit view with the following structure:

@extends('web.post.layout')@section('main')
<form method="post">
@csrf
@method('patch')

<input type="text" name="title" value="{{ old('title'}}">
<textarea name="body" value="{!! old('title' !!}">
        @include('web.post.subviews.tags')
@include('web.post.subviews.cover')
        <button type="submit">Update post</button>
</form>
@endsection

Seems very simple, specially when the tags and cover image management are done separately in their own subview. You don’t have to bloat the view with something you will barely edit or uses 30 lines of code.

Components

By default Laravel finds Components inside the resources/views/components. I consider Components as self-contained views that can injected into anything and won’t break unless you pass something you shouldn’t.

For example, the post-card.blade.php requires a App\Post model instance, and shows something like the post resume:

Frontend vs Backend

Sometimes it’s better to separate your Frontend (aka, public facing views) from the Backend (admin app-breaking panel).

This would allow your views to exclude logic related from the frontend area, and have more freedom on what you can do in the backend, specially taking away the role/permission architecture away from the frontend.

views/
└── web/
├── frontend
│ ├── layout
│ ├── components
│ ├── profile
│ └── post
└── backend
├── layout
├── user
├── post
└── comments

The same principles apply, since you are only one additional directory deep now. You are free to separate the layout for the frontend and backend if you need to, may be because you can change and update the frontend separately from the backend.

And that’s practically it. Happy organization of your views.

2021년 1월 18일 월요일

Using the SetCacheHeaders middleware

 

  • no-cache and etag will allow the user to refresh the page (even before the expiration time) without downloading the whole page if the latest published podcasts are still the same.
  • private says the homepage is per-user, and should be cached only in the user device rather than, for example, a proxy.
  • max-age=300 will set an expiration time of 5 minutes, since after that time surely there is a new Podcast published.

Route::get('/', 'PodcastController@index')
->middleware('cache.headers:no-cache,private,max-age=300;etag');