美文网首页
Laravel CURD 例子

Laravel CURD 例子

作者: 王宣成 | 来源:发表于2024-07-30 14:30 被阅读0次
    // -m 生成迁移文件
    php artisan make:model Post -m
    php artisan make:controller PostController --resource
    php artisan make:resource PostResource
    

    控制器

    <?php 
    use App\Http\Resources\PostResource;
    use App\Models\Post;
    use Illuminate\Http\Request;
    use Illuminate\Validation\ValidationException;
    use Illuminate\Database\Eloquent\ModelNotFoundException;
    
    class PostController extends Controller
    {
        // 列表 (Index)
        public function index(Request $request)
        {
            $query = Post::query();
    
            // 搜索条件
            if ($request->has('search')) {
                $search = $request->input('search');
                $query->where('title', 'like', "%{$search}%")
                      ->orWhereHas('user', function ($q) use ($search) {
                          $q->where('name', 'like', "%{$search}%");
                      })
                      ->orWhereHas('email', function ($q) use ($email) {
                          $q->where('email',  $email);
                      });
            }
    
            // 排序
            $sortBy = $request->input('sort_by', 'created_at');
            $sortOrder = $request->input('sort_order', 'desc');
            $query->orderBy($sortBy, $sortOrder);
    
            // 分页
            $perPage = $request->input('per_page', 10);
            $posts = $query->with(['user', 'category'])->paginate($perPage);
    
            return PostResource::collection($posts);
        }
    
        // 创建 (Create)
        public function store(Request $request)
        {
            try {
                $validated = $request->validate([
                    'title' => 'required|string|max:255',
                    'content' => 'required|string',
                    'user_id' => 'required|exists:users,id',
                    'category_id' => 'required|exists:categories,id',
                ]);
    
                $post = Post::create($validated);
    
                return new PostResource($post);
            } catch (ValidationException $e) {
                return response()->json(['error' => $e->errors()], 422);
            } catch (\Exception $e) {
                return response()->json(['error' => 'An error occurred while creating the post.'], 500);
            }
        }
    
        // 读取 (Read)
        public function show($id)
        {
            try {
                $post = Post::findOrFail($id);
                return new PostResource($post);
            } catch (ModelNotFoundException $e) {
                return response()->json(['error' => 'Post not found'], 404);
            } catch (\Exception $e) {
                return response()->json(['error' => 'An error occurred while retrieving the post.'], 500);
            }
        }
    
        // 更新 (Update)
        public function update(Request $request, $id)
        {
            try {
                $validated = $request->validate([
                    'title' => 'required|string|max:255',
                    'content' => 'required|string',
                    'user_id' => 'required|exists:users,id',
                    'category_id' => 'required|exists:categories,id',
                ]);
    
                $post = Post::findOrFail($id);
                $post->update($validated);
    
                return new PostResource($post);
            } catch (ValidationException $e) {
                return response()->json(['error' => $e->errors()], 422);
            } catch (ModelNotFoundException $e) {
                return response()->json(['error' => 'Post not found'], 404);
            } catch (\Exception $e) {
                return response()->json(['error' => 'An error occurred while updating the post.'], 500);
            }
        }
    
        // 删除 (Delete)
        public function destroy($id)
        {
            try {
                $post = Post::findOrFail($id);
                $post->delete();
    
                return response()->json(null, 204);
            } catch (ModelNotFoundException $e) {
                return response()->json(['error' => 'Post not found'], 404);
            } catch (\Exception $e) {
                return response()->json(['error' => 'An error occurred while deleting the post.'], 500);
            }
        }
    }
    

    模型

    <?php
    // app/Models/Post.php
    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Database\Eloquent\Factories\HasFactory;
    
    class Post extends Model
    {
        use HasFactory;
    
        protected $fillable = ['user_id', 'category_id', 'title', 'content'];
    
        public function user()
        {
            return $this->belongsTo(User::class);
        }
    
        public function category()
        {
            return $this->belongsTo(Category::class);
        }
    }
    
    
    <?php
    // app/Models/User.php
    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Database\Eloquent\Factories\HasFactory;
    
    class User extends Model
    {
        use HasFactory;
    
        protected $fillable = ['name', 'email', 'password'];
    
        public function posts()
        {
            return $this->hasMany(Post::class);
        }
    }
    
    
    <?php
    // app/Models/Category.php
    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Database\Eloquent\Factories\HasFactory;
    
    class Category extends Model
    {
        use HasFactory;
    
        protected $fillable = ['name'];
    
        public function posts()
        {
            return $this->hasMany(Post::class);
        }
    }
    
    

    资源

    <?php 
    namespace App\Http\Resources;
    
    use Illuminate\Http\Resources\Json\JsonResource;
    
    
    
    /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request)
    {
        // 自动返回模型的所有字段
        $data = parent::toArray($request);
    
        // 添加自定义字段
        $data['user'] = new UserResource($this->whenLoaded('user'));
        $data['category'] = new CategoryResource($this->whenLoaded('category'));
    
        return $data;
    
        //return [
        //  'id' => $this->id,
        //  'title' => $this->title,
        //  'content' => $this->content,
        //];
    
    }
    
    

    路由

    use App\Http\Controllers\PostController;
    
    Route::apiResource('posts', PostController::class);
    
    

    相关文章

      网友评论

          本文标题:Laravel CURD 例子

          本文链接:https://www.haomeiwen.com/subject/cbkghjtx.html