Select model methods in the Laravel controller index method?

3

I have an index method that fetches all events in the database and shows them in a table

Model Event:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Event extends Model
{
    protected $fillable = [
        'title', 
        'description', 
        'start_datetime',
        'end_datetime',
    ];

    public function getTodayEvents()
    {

    }

    public function getFiveDaysEvents()
    {

    }
}

Route:

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

Route::get('/home', 'HomeController@index')->name('home');
Route::get('/profile', 'Auth\UserController@profile')->name('profile');
Route::post('/profile', 'Auth\UserController@updateProfile')->name('updateProfile');

Route::get('event/index/{filter}', 'EventController@index')->name('indexEvent');
Route::get('event/create', 'EventController@create')->name('createEvent');
Route::post('event/store', 'EventController@store')->name('storeEvent');
Route::get('event/show/{id}', 'EventController@show')->name('showEvent');
Route::get('event/edit/{id}', 'EventController@edit')->name('editEvent');
Route::post('event/update/{id}', 'EventController@update')->name('updateEvent');
Route::get('event/destroy/{id}', 'EventController@destroy')->name('destroyEvent');

});

EventController: '

public function index()
{
    $events = Event::all();
    return view('event.index')->with('events', $events);
}

In this table that displays the events I have a dropdown menu to display all events, today's events and events for the next 5 days

View index:

@extends('layouts.app')
@section('title', 'Eventos')
@section('content')
<div class="container">
<div class="panel panel-primary">
    <div class="panel-heading">Eventos</div>
    <div class="panel-body">
        <div class="row">
            <div class="col-lg-11">
                <a class="btn btn-primary" href="{{ route('createEvent') }}" role="button">Novo Evento</a>
            </div><!-- /.col-lg-6 -->
            <div class="col-lg-1">
                <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                    Filtrar <span class="caret"></span>
                </button>
                <ul class="dropdown-menu">
                    <li><a href="{{ route('indexEvent', ['filter' => 'all']) }}">Todos os eventos</a></li>
                    <li><a href="{{ route('indexEvent', ['filter' => 'today']) }}">Eventos de hoje</a></li>
                    <li><a href="{{ route('indexEvent', ['filter' => 'five']) }}">Eventos nos próximos 5 dias</a></li>
                </ul>
            </div><!-- /.col-lg-6 -->
        </div><!-- /.row -->
    </div>
    <table class="table table-bordered">
        <tr>
            <th>Título</th>
            <th>Detalhes</th>
            <th>Alterar</th>
            <th>Excluir</th>
        </tr>
        @foreach($events as $event)
        <tr>
            <td>{{ $event->title }}</td>
            <td>
                <a href="{{ route('showEvent', $event->id) }}" class="fa fa-file-text-o" aria-hidden="true"></a> 
            </td>         
            <td>
                <a href="{{ route('editEvent', $event->id) }}" class="fa fa-pencil" aria-hidden="true"></a>
            </td>
            <td>
                <a href="{{ route('destroyEvent', $event->id) }}" class="fa fa-trash" aria-hidden="true"></a>
            </td>
        </tr>
        @endforeach
    </table>
</div>
</div>
@endsection

So far so good, my question is that I have both methods getTodayEvents() and getFiveDaysEvents() and I would like to know how I could select the method I want from the link in view and use only a index in EventController instead of creating 3 methods index each with a method of model Event ?

    
asked by anonymous 14.08.2017 / 00:10

1 answer

3

You can use the following in your% w / o of% put a parameter with a default value, eg:

public function index($filter = null)
{
    if (is_null($filter))
    {
        $events = Event::all();
    }
    else
    {
        $events = Event::where('campo_filtro', $filter)->get();
    }
    return view('event.index')->with('events', $events);
}

would be the ideal and much used by index developers. You can also work with local scope of instead of creating methods of the form of your question, for example:

class Event extends Model
{
    protected $fillable = [
        'title', 
        'description', 
        'start_datetime',
        'end_datetime',
    ];

    public function scopeGetEvents($query, $filter)
    {            
        if ($filter == 'today')
        {
            return $query->getEventsToday($query);
        }
        if ($filter == 'five')
        {
            return $query->getEventsFive($query);
        }
        return $query;
    }
    public function scopeGetEventsToday($query)
    {
         return $query-> //... code;
    }
    public function scopeGetEventsFive($query)
    {
         return $query-> //... code;
    }
}

and thus use in its PHP method controller

public function index($filter = null)
{
    $events = Event::getEvents($filter)->get();
    return view('event.index')->with('events', $events);
}

Note: filter_field is the field you want to filter, and the variable index would be the corresponding value. This is an example that fits in a general way in your code, since the information is few.

The route example route:

Route::get('event/index/{filter?}', ['as' => 'indexEvent', 
                                     'uses' => 'EventController@index']);

and link :

<li>
   <a href="{{ route('indexEvent', ['all']) }}">Todos os eventos</a>

14.08.2017 / 00:53