justin0122 / crud
crud - 一个简单的Laravel包。
dev-main
2024-06-12 15:58 UTC
README
依赖关系
此包需要以下依赖
安装
Composer
composer require justin0122/crud
Zip文件夹
将packages目录复制到项目的根目录。添加
//composer.json "require": { ... "justin0122/crud": "*" }, ... "minimum-stability": "dev", "prefer-stable": true, "repositories": [ { "type": "path", "url": "packages/justin0122/crud" } ], ]
运行
composer dump-autoload composer update
将服务提供者添加到config/app.php文件中
# config/app.php 'providers' => [ ... \Justin\Crud\CrudServiceProvider::class, ... ],
使用方法
要生成CRUD,运行以下命令
php artisan crud:make Post
这将生成以下文件
app/Livewire/Post.php
app/Livewire/Posts.php
app/Models/Post.php
database/migrations/2021_01_01_000000_create_posts_table.php
resources/views/livewire/posts/index.blade.php
resources/views/livewire/crud/create.blade.php
resources/views/livewire/crud/edit.blade.php
详细信息
表单
表单使用模型中的$fillables
数组创建。如果您想添加更多字段,只需将它们添加到模型中的数组中即可。
视图
由于表单是动态生成的,它们被设置为全局。这意味着您也可以在其他视图中使用它们。视图位于resources/views/livewire/crud
文件夹中。
添加可填充字段
为了让CRUD工作,您需要在模型中添加可填充字段
# app/Models/Post.php protected $fillable = [ 'title', 'body', ];
添加路由
在web.php文件中添加路由
# routes/web.php use App\Http\Livewire\Post; Route::get( '/post', function () { return view('post'); } )->name('post');
添加Livewire组件
将Livewire组件添加到视图中
<!-- resources/views/post.blade.php --> <livewire:post />
显示帖子
要在视图中显示帖子,您可以硬编码要显示的字段,否则将显示可填充数组中的第二个字段作为标题,第三个字段作为描述。
<!-- resources/views/livewires/posts/index.blade.php --> @foreach($results as $result) <x-card :title="$result->title ?? ''" :title-classes="'text-2xl'" :description="Str::limit($result->body, 100) . '' ?? ''" :image="$result->image ?? 'https://placehold.co/1200x1200'" :button="['url' => '/post?id=' . $post->id, 'label' => 'View'] ?? ''" :deleteButton="['id' => $result->id] ?? ''" /> @endforeach
默认
@foreach($results as $result) @php $attributes = $result->getAttributes(); $title = $attributes[array_keys($attributes)[1]]; $body = $attributes[array_keys($attributes)[2]]; @endphp <x-card :title="$title ?? ''" :title-classes="'text-2xl'" :description="Str::limit($body, 100) . '' ?? ''" :image="$result->image ?? 'https://placehold.co/1200x1200'" :button="['url' => url()->current() . '?id=' . $result->id, 'label' => 'View'] ?? ''" :deleteButton="['id' => $result->id] ?? ''" /> @endforeach