How could a search engine in laravel 5.1?

2

Good friends, the question is simple, I need to do a search engine in laravel but the way I'm doing it, complicates me a bit because I'm doing the following:

currently in the controller I have this:

public function index(Request $request)
{

    $events = Event::Events();

    return view('event.index', compact('events'));
}

Which I send to the index and lists the categories with the method:

public static function Events(){
    return DB::table('events')
    ->join('categories', 'categories.id', '=', 'events.category_id')
    ->select('events.*', 'categories.name_cat')
    ->get();
}

The question is that I am trying to do with a scope the search engine but the problem is that I have the method I need to list the categories, since it has the query and I do not know how to use the scope and also the Events method, as I think doing it is something like this:

public function index(Request $request)
{

    $events = Event::name($request->get('name_eve'))->orderBy('id','DESC')->paginate(2);
    return view('event.index', compact('events'));
}

Which works for me, but the problem is that it does not show me the category in the index because I need to use the Events method.

    
asked by Susje 16.07.2017 в 05:31
source

1 answer

2

Assuming that you have created the models Event and Category , and that their relationship is one to many, you could solve it easily thanks to the dynamic properties of Eloquent and Eager loading.

The first thing is that I see that the Events() method is unnecessary, instead of creating and using that method, you can simply do it (assuming that the relationship in the Event model is called 'category':

$events = Event::with('category')->all();

From what I see, I think you're going to do a scope to search by name of the event, which would be something like this:

public function scopeName($query, $name)
{
    return $query->where('name', $name);
}

You would load the list of categories in this way:

$events = Event::with('category')->name($request->get('name_eve'))->orderBy('id','DESC')->paginate(2);

(Although I have a doubt and I do not remember if you can do Eager Loading within the scope, that's why I left it out)

The name of the category you would get as a property of the event object:

$event->category->name_cat
    
answered by 16.07.2017 / 07:26
source