Home > PHP Framework > Laravel > laravel search delete

laravel search delete

PHPz
Release: 2023-05-21 10:10:36
Original
517 people have browsed it

Laravel search and delete is a very common development requirement, especially when developing applications such as content management systems or e-commerce websites that require CRUD operations on data. Laravel, as a popular PHP framework, provides a wealth of tools and APIs, making this process very simple.

1. Laravel Search

Implementing the search function in Laravel usually requires the following steps:

  1. Install Laravel Scout

Laravel Scout Suitable for applications that classify and optimize search results, Scout is faster than native search queries, and query components are easier to reconstruct. Laravel Scout uses Elasticsearch or Algolia to perform searches, these search engines are very popular and have extensive community support.

  1. Database Migration

Based on establishing the Model, Controller and database migration files in the Laravel application, we need to perform search-related database migration operations.

For example, in the user database we can add a "searchable" column:

Schema::table('users', function (Blueprint $table) {
    $table->boolean('searchable')->default(false);
});
Copy after login

Here we can set the default value false for searchable, that is, the user does not want to be searched. It can also be configured to set searchable to true after editing the user information, so that the user can be searched.

  1. Use Scout to mark the model

When using Laravel Scout, we need to use the Searchable trait in the corresponding Model.

For example:

namespace App;

use IlluminateDatabaseEloquentModel;
use LaravelScoutSearchable;

class User extends Model
{

use Searchable;

// ...
Copy after login

}

After this process is completed, the model's save(), delete(), restore() and forceDelete() methods will automatically synchronize with the search engine.

  1. Using Algolia or ElasticSearch

Create indexes and format search results in Algolia or ElasticSearch. To optimize search results, we can use Scout's Searchable trait in Laravel.

For example, in Algolia:

namespace App;

use LaravelScoutSearchable;
use AlgoliaScoutExtendedSearchableAggregator;

class Note extends Model
{

use Searchable, Aggregator;

public function toSearchableArray()
{
    $array = $this->toArray();

    // 请求注入时,我们需要更新查询升级和向量分配
    $array = $this->seoInject Boosts($array, [
        'title' => 1000, 
        'content' => 100,
        'body' => 10,
    ]);

    return $array;
}
Copy after login

}

2. Laravel Search and Delete

In Laravel’s CRUD applications, deletion operations are very common. Removal from search results is a relatively complex task as you need to have the deleted data automatically removed from the search engine. This means that we need to operate the database.

The following is the general process for searching and deleting data:

1. Select the data to be deleted in the search results.

2. Mark this data as "delete", update the database, and delete this data from the search engine.

namespace AppHttpControllers;

use AppNote;
use IlluminateHttpRequest;

class NoteController extends Controller
{

/**
 * 删除一条笔记修饰符信息请求
 *
 * @param int $id
 * @return IlluminateHttpResponse
 */
public function destroy($id)
{
    $note = Note::find($id);

    if ($note) {
        // 从数据库中删除
        $note->delete();

        // 从搜索引擎中删除
        $note->unsearchable();
    }

    return redirect()
        ->route('notes.index')
        ->with('success', 'Note deleted successfully.');
}
Copy after login

}

In the above example, we deleted the note from the database and deleted it from the search engine. Next, we’ll discuss how to implement bulk deletions in search results.

3. Implement batch deletion operations

Before deleting multiple results, we need to develop a multi-select box and delete button on the front end. Then, we need to implement the batch delete operation in the controller. This part of the code includes:

  1. Get all the notes to be deleted.
  2. Mark these notes as "Delete" in the database.
  3. Remove these notes from search engines.
  4. Redirect to the original route.

For example, in the NoteController.php file, implement batch deletion operations:

/**
 * 删除多条笔记发生请求
 *
 * @param Request $request
 * @return IlluminateHttpResponse
 */
public function multiDestroy(Request $request)
{
    $notesId = $request->ids;

    foreach ($notesId as $noteId) {
        $note = Note::find($noteId);
        if ($note) {
            $note->delete();
            $note->unsearchable();
        }
    }

    return redirect()
        ->route('notes.index')
        ->with('success', 'Notes were deleted successfully.');
}
Copy after login

In the above code, we traverse all the note objects to be deleted, and delete them in the database and They are marked for deletion in search engines. This process is very similar to single deletion.

4. Summary

This article introduces how to implement search and delete in Laravel applications, covering the basic usage and controller processing methods of the Laravel framework and Scout module. You can use this example to implement the same function in your own Laravel application, making your development more convenient.

The above is the detailed content of laravel search delete. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template