简体   繁体   中英

Inputting to a Controllers closure in laravel 5.2

So i have a 'TicketController' which holds my functions for manipulating 'tickets' in a system. I am looking to work out the best way to send my new route that will take a route parameter of {id} to my TicketController to view a ticket.

Here is my route set

    Route::group(['middleware' => 'auth', 'prefix' => 'tickets'], function(){

    Route::get('/', 'TicketController@userGetTicketsIndex');
    Route::get('/new', function(){
       return view('tickets.new');
     });
    Route::post('/new/post', 'TicketController@addNewTicket');
    Route::get('/new/post', function(){
       return view('tickets.new');
    });
    Route::get('/view/{id}', function($id){
        // I would like to ideally call my TicketController here
    });
 });

Here is my ticket controller

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Ticket;
use App\User;

class TicketController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Returns active tickets for the currently logged in user
     * @return \Illuminate\Http\Response
     */
    public function userGetTicketsIndex()
    {
        $currentuser = \Auth::id();
        $tickets = Ticket::where('user_id', $currentuser)
            ->orderBy('updated_at', 'desc')
            ->paginate(10);
        return view('tickets.index')->with('tickets', $tickets);
    }

    public function  userGetTicketActiveAmount()
    {
        $currentuser = \Auth::id();
    }

    public function addNewTicket(Request $request)
    {
        $this->validate($request,[
            'Subject' => 'required|max:255',
            'Message' => 'required|max:1000',
        ]);
        $currentuser = \Auth::id();
        $ticket = new Ticket;
        $ticket->user_id = $currentuser;
        $ticket->subject = $request->Subject;
        $ticket->comment = $request->Message;
        $ticket->status = '1';
        $ticket->save();
     }

 public function viewTicketDetails()
 {
   //retrieve ticket details here
 {

}

You don't need to use closure here. Just call an action:

Route::get('/view/{id}', 'TicketController@showTicket');

And in TicketController you'll get ID:

public function showTicket($id)
{
    dd($id);
}

More about this here .

You should use type-hint in laravel. Its awesome
In route

Route::get('/view/{ticket}', 'TicketController@viewTicketDetails');

In controller

public function viewTicketDetails(Ticket $ticket)
 {
   //$ticket is instance of Ticket Model with given ID
   //And you don't need to $ticket = Ticket::find($id) anymore
 {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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