jeudi 1 août 2019

With the input value, query whether the category contains the name or the company name. I want to return the company list

With the input value, query whether the category contains the name or the company name. I want to return the company list.

Controller:

public function query(Request $request)
{
    $search = $request->what;
    $companies = Company::where('deleted_at', null);

    if ($search) {
        $categories = Category::where('deleted_at', null);
        $comp = [];
        foreach ($categories as $category) {
            if (Str::contains(mb_strtolower($category->name), mb_strtolower($search)))
                array_push($comp, $category->company);
        }

        return $comp;
    }
}

Category model:

public function companies()
{
    return $this->hasMany('App\Company', 'category_id', 'id');
}

Company model:

public function category()
{
    return $this->belongsTo('App\Category', 'category_id', 'id')->withDefault([
        'name' => '-']);
}

Category migration:

 Schema::create('categories', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('upper_id')->default(0);
        $table->string('name', 100);
        $table->string('slug', 100);
        $table->string('description', 500)->nullable();
        $table->timestamps();
        $table->softDeletes();
    });

Company migration:

Schema::create('companies', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('category_id');
        $table->string('name', 100);
        $table->string('slug', 100);
        $table->timestamps();
        $table->softDeletes();

        $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
    });



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire