Select model methods in the Laravel controller index method?

Asked

Viewed 1,445 times

3

I have an index method that searches all events in the database and shows 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 the events, the events of today and the events of 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 doubt is that I have both methods getTodayEvents() and getFiveDaysEvents() and would like to know how you could select the method I want from the link on view and use only one method index in Eventcontroller instead of creating 3 methods index each with a method of model Event?

  • Pass as a parameter in the URL a value that will identify the desired results. See the function documentation route

  • I even passed route('indexEvent', ['typel' => 'all']) but what about the rest? In the index method? If you know and can post a reply.

  • In the method index you treat this value with a switch/case, for example.

1 answer

3


You can use the following in your index put a parameter with a value pattern, example:

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 widely used way by developers PHP. You can also work with local Scope of instead of creating methods in 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 use it in your controller method index

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

Observing: field filter is the field you want to filter, and the variable $filter 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::get('event/index/{filter?}', ['as' => 'indexEvent', 
                                     'uses' => 'EventController@index']);

and in the link:

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

References:

  • And in the view I leave it the way that this only passing the filter parameter?

  • In the view I put in this way <li><a href="{{ route('indexEvent', ['filter' => 'all']) }}">All events</a></li> <li><a href="{{ route('indexEvent', ['filter' => 'Today']) }}">Today’s events</a></li> <li><a href="{{ route('indexEvent', ['filter' => 'five']) }}">Events in the next 5 days</a></li> and Route::get('Event/index/{filter}', 'Eventcontroller@index')->name('indexEvent'); but I think I’m doing something wrong.

  • I’ll put the full view.

  • What is the difference between Route::get('Event/index/{filter? }', ['as' => 'indexEvent', 'uses' => 'Eventcontroller@index']); to Route::get('Event/index/{filter? }', 'Eventcontroller@index');

Browser other questions tagged

You are not signed in. Login or sign up in order to post.