M
M
Maxim Spiridonov2014-12-07 09:09:27
Laravel
Maxim Spiridonov, 2014-12-07 09:09:27

How to stick comments to the news?

There was a need to add comments to the news, but I don’t quite understand how to implement this correctly in Larvel. I implemented it like this (code below), but I thought about it and decided that this is most likely not the right decision in terms of logic.
In general, I did everything in the same controller and model that is responsible for displaying news.
Did so. I also took it in TicketController, which is responsible for displaying posts, and wrote the following code (below is the entire ticket controller code, but with explanations).

<?php

class TicketController extends BaseController {
    
    public static function Index(){
        $tickets = Site::selectTicket();
         return View::make('cabinet.tickets')->with(['tickets' => $tickets]);
    }
    
    public static function getTicket($id){
        $id = (int)$id;
        $comments = Ticket::getComment($id); // Принимаю комментарии из бд
        $show_ticket = Ticket::get($id); // Принимаю новость из бд
        return View::make('cabinet.show_ticket')->with(['show_ticket' => $show_ticket, 'comments' => $comments]);
    }

    // Добавление тикета
    public function addTicket(){
        
        $data = Input::all();
        
        $rules = [
          'title' => 'required|min:10', 
          'description' => 'required|min:10'
        ];
        
        $val = Validator::make($data, $rules);
        
        if($val->fails()){
            
            return Redirect::back()->withErrors($val, 'addticket');
            
        }
        
        $ticket = Ticket::add($data);
        
         if($ticket instanceof Exception){
            return 'Ошибка при добавлении тикета';
        }
        
        return Redirect::to('/cabinet');
        
    }
    
    
    // Добавление тех самых комментариев к новости
    public function addComment(){
        
        $data = Input::all();
        
        $rules = [
          'description' => 'required|min:10',
        ];
        
        $val = Validator::make($data, $rules);
        
        if($val->fails()){
            
            return Redirect::back()->withErrors($val, 'addComm');
            
        }
        
        $ticket = Ticket::addComm($data);
        
         if($ticket instanceof Exception){
            return 'Ошибка при добавлении комментария';
        }
        
        return Redirect::to('/cabinet');
    }
        
}

Well, actually the Ticket model itself.
<?php

class Ticket extends Eloquent {

    public static $unguarded = true;

    //Получаем все тикеты из бд
    public static function selectTicket() {
        $tickets = Ticket::where('owner', '=', Auth::user()->email)->orderBy('title', 'desc')->take(3)->get();
        return $tickets;
    }

    //Получаем определенный тикет методом GET
    public static function get($id) {
        $show_ticket = Ticket::where('id', '=', $id)->firstOrFail();
        return $show_ticket;
    }

    // Получаем комментарии к тикету из базы данных
    public static function getComment($id) {
        $comments = DB::select('select * from tickets_comments where ticket_id = ?', [$id]);
        return $comments;
    }

    // Добавляем тикет
    public static function add($data) {

        try {
            $ticket = Ticket::create([
                        'title' => $data['title'],
                        'description' => $data['description'],
                        'owner' => Auth::user()->email
            ]);
        } catch (Exception $ex) {
            return $ex;
        }

        return $ticket;
    }

    // Добавляем комментарий к тикету
    public static function addComm($data) {

        try {            
           $ticket = DB::insert('insert into tickets_comments (ticket_id, description, owner) values (?, ?, ?, ?)'
                    , [1, $data['description'], Auth::user()->email]);
            
        } catch (Exception $ex) {
            return $ex;
        }

        return $ticket;
    }

}

I would like to hear advice on how to implement all this differently (in the mind). I thought about creating a separate controller for comments + a separate model, but I don’t know how to display comments later. I would be very grateful for any help.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gladkovskiy, 2014-12-07
@SMGladkovskiy

Take advantage of Eloquent - make connections.
Tickets
DB table: tickets
Model: Tiket
Relationships: Has a lot of comments
Comments
Table: comments
Model: Comment
Relationships: Owned by Tickets (belongsTo)
Prescribe everything and then to get an article with comments:
Comments can be obtained through
In general, read the manual - everything you need is described there.

F
FanatPHP, 2014-12-07
@FanatPHP

There are two options to learn something:
- either read a book
- or learn by example
When you look at the unfortunate model, bloody tears well up in your eyes.
A more or less modern technological installation is simply disfigured by the blows of a barbarian club. WELL AT LEAST TO SEE HOW IT IS DONE IN THE NEIGHBOR METHOD and it was possible not to sculpt SQL with your hands? Give Laravel to the classic pohapa-monkey - she will make the usual mysql_query out of it.
In order to somehow rehabilitate yourself, you must come to the employer, admit that you deceived him and you don’t understand Laravel at all. After that, you sit down to study at least Code Bright, and only after you have finished the book and completed all the examples, you can start trying to climb into someone else's code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question