關於Laravel Component 和 Model的建立規則

2022-10-25
alt text

Laravel Component的建立規則:

建立Cmd
php artisan make:component News

注意: 字首一定要大寫,不然Laravel不會去調用

如不透過Cmd,想在已經建立好的Component view中加入該component view對應的class,操作方式:
  1. 到資料夾 APPViewComponents
  2. 建立"字首為大寫的"Component,如: News.php
News.php
=======

<?php
namespace AppViewComponents;
use IlluminateViewComponent;

class News extends Component
{
    /**
     * Create a new component instance.
     *
     * @return void
     */
    public function __construct()
    {
        //這邊是接收資料
    }
    /**
     * Get the view / contents that represent the component.
     *
     * @return IlluminateContractsViewView|Closure|string
     */
    public function render()
    {
        //這邊是呼叫view
        return view('components.news');
    }
}

調用方式:
在blade中使用以下方式調用
<x-News />

如果要送參數則可寫成
blade
=====================

<x-News var="123" :array="['var1'=> 1, 'var2' => 2]" />

=======================
Component Class:
AppViewComponentsNews.php
=======================
.
.
.
public function __construct($var, $array)
{
        //這邊是接收資料
       $this->var =  $var;
       $this->array = $array;
}

public function render()
{
        //這邊是接收資料
       $data =  [
           'var' => $this->var,
           'array' => $this->array
       ];

       return view('components.news', compact('data'));
}
.
.
.
=========================
Component Blade:
ResourceViewComponents ews.php
=========================
<div>{{ $data['var'] }}</div>

@foreach ($data['array'] as $item)
<div>{{ $item }}</div>
@endforeach


 

Contact

Github

Codepen

歡迎參觀我的賣場
© 2013 Copyright Digishot Web | Design Tools
Visitors【704265】
digishot webdesign studio