繁体   English   中英

如何从Laravel中的另一个控制器获取信息

[英]how to get information from another controller in laravel

我想使用另一个控制器保存信息以将其存储在数据库中。
在我的情况下,有两个控制器:

  • PostingsController
  • 评论控制器

我可以使用CommentsController来创建注释的创建函数,但是无法从CommentsController中将post_id保存在数据库中。 我想使用PostingsController保存post_id,因为它具有:

//if user did not fill the form properly
    //error messages will popup
    $this->validate($request, [
        'comment' => 'required',
    ]);

    //if user filled the form properly
    //store the form
    $comment = new Comment();
    //for connecting both user and comment
    $comment->user_id = Auth::id();

    //to store comment
    $comment->post_id = //I want to save post_id from PostingsController
    //to store comment
    $comment->comment = $request->input('comment');
    //save all user input
    $comment->save();
    dd($comment);

我设置了$ comment = Posting :: id();,但是它不起作用。 错误是:

BadMethodCallException
Call to undefined method App\Models\Posting::id()


我的PostingsController:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Posting;
use App\User;
use Illuminate\Support\Facades\Auth;

class PostingsController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth');
    }


    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //this is how to get all posting, but this shows only all posting
        // $postings = Posting::all();
        // $postings->load('user');
        //this is how to get all posting with created_at and descending order.
        $postings = Posting::orderBy('created_at', 'desc')->get();
        //should be function name
        $postings->load('user');


        return view('index')->with('postings', $postings);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //if user did not fill the form properly
        //error messages will popup
        $this->validate($request, [
            'posting' => 'required',
        ]);

        //if user filled the form properly
        //store the form
        $posting = new Posting();
        //for connecting both user and posting
        $posting->user_id = Auth::id();
        //to store posting
        $posting->post = $request->input('posting');
        //save all user input
        $posting->save();

        return redirect()->to('/home')->with('success', 'Posting created successfully!');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $posting = Posting::find($id);
        return view('show')->with('posting', $posting);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //this is the way how to find posting of authenticated user
        $posting = Posting::find($id);

        return view('edit')->with('posting', $posting);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //if user did not fill the form properly
        //error messages will popup
        $this->validate($request, [
            'posting' => 'required',
        ]);

        //if user filled the form properly
        //store the form
        $posting = Posting::find($id);
        //to store posting
        $posting->post = $request->input('posting');
        //save all user input
        $posting->save();

        return redirect()->to('/home')->with('success', 'Posting edited successfully!');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $posting = Posting::find($id);
        $posting->delete();

        return redirect()->to('/home')->with('success', 'Posting deleted successfully');
    }


}

我的CommentsController:

<?php

namespace App\Http\Controllers;
use App\Models\Posting;
use App\Models\Comment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class CommentsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('comments.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //if user did not fill the form properly
        //error messages will popup
        $this->validate($request, [
            'comment' => 'required',
        ]);

        //if user filled the form properly
        //store the form
        $comment = new Comment();
        //for connecting both user and comment
        $comment->user_id = Auth::id();

        //to store comment
        $comment->post_id = //problem
        //to store comment
        $comment->comment = $request->input('comment');
        //save all user input
        $comment->save();
        dd($comment);

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

视图中的create.comments:

@extends('layouts.app')
@section('content')
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">
                    <div class="float-left m-2">Create new comment</div>
                    <span class=" "><a href="/home" class="float-right btn btn-primary">Go back</a></span>
                </div>

                <div class="card-body">
                    @if (session('status'))
                        <div class="alert alert-success" role="alert">
                            {{ session('status') }}
                        </div>
                    @endif

                    <form method="post" action="/comments" >

                        @csrf
                        <input type="hidden" name="post_id" id="post_id" value="{{ $post->id }}" />
                        <div class="form-group">
                            <input type="text" class="form-control" name="comment" id="comment" placeholder="Comment what you think!">
                        </div>
                        <button type="submit" class="btn btn-primary float-right">Comment</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
@endsection

遵循关注分离的原理,您可以将逻辑移到另一个模块(例如服务)中

我建议添加一个新的文件夹app/services ,并为每个需要实现的逻辑添加一个服务类,例如。 app/services/AddCommentToPostService.php

这也将使系统的测试更加容易。

您可以使用应用程序方法在laravel app('App \\ Http \\ Controllers \\ ControllerName')-> functionName()中调用另一个控制器的控制器方法;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM