0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Rails7 とLaravel10】controllerを担うファイルの記述方法比較

Last updated at Posted at 2024-09-08

前提

両者Postモデルを作成してあります。基本的なcrudを実装する想定です

比較

laravelと比較したrailsの特徴

・ドット記法が使われる
・モデルのインポート文不要
・pythonに近い構文
・ormはlaravelと似ており、直感的
・ファイル名はスネークケース

posts_controller.rb
class Api::V1::PostsController < ApplicationController
  def index
    @posts = Post.all
    render json: @posts
  end

  def show
    @post = Post.find(params[:id])
    render json: @post
  end

  def create
    @post = Post.new(post_params)
    
    if @post.save
      render json: @post
    else
      render json: @post.errors, status: :unprocessable_entity
    end
  end

  def update
    @post = Post.find(params[:id])
    if @post.update(post_params)
      render json: @post
    else
      render json: @post.errors, status: :unprocessable_entity
    end
  end

  def destroy
    @post = Post.find(params[:id])
    @post.destroy
  end

  private

  def post_params
    params.require(:post).permit(:title,:content)
  end
  
end

railsと比較したlaravelの特徴

・アロー演算子が使われる
・JavaScriptに近い構文
・rails同様ormは直感的
・ファイル名(クラス名)はパスカルケース

PostController.php
<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\Post;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class PostController extends Controller
{
    public function index()
    {
        $posts = Post::all();
        return response()->json($posts);
    }

    public function show($id)
    {
        $post = Post::findOrFail($id);
        return response()->json($post);
    }

    public function store(Request $request)
    {
        $post = new Post();
        $post->title = $request->title;
        $post->content = $request->content;

        if ($post->save()) {
            return response()->json($post);
        } else {
            return response()->json(['error' => 'Unprocessable Entity'], 422);
        }
    }

    public function update(Request $request, $id)
    {
        $post = Post::findOrFail($id);
        $post->title = $request->title;
        $post->content = $request->content;

        if ($post->save()) {
            return response()->json($post);
        } else {
            return response()->json(['error' => 'Unprocessable Entity'], 422);
        }
    }

    public function destroy($id)
    {
        $post = Post::findOrFail($id);
        $post->delete();

        return response()->json(['message' => 'Post deleted successfully']);
    }
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?