【问题标题】:Delete products url not working in Laravel删除产品 url 在 Laravel 中不起作用
【发布时间】:2019-10-27 13:55:02
【问题描述】:

我希望用户在单击不同按钮时删除产品,但我收到错误404 url not found,但我有 url。

如果我把dd($product) 放在$like = Like::findOrFail($product); 之前 它显示id(4),但如果我输入dd($like),则会引发错误404。我怎样才能使这个功能起作用?。

控制器

 public function destroy($product)
 {
   $like = Like::findOrFail($product);
     dd($like);
   $like->delete();

  return 'done';
 }

刀片

  <a class="remove"  href="{{ route('product.unlike', ['product' => $product->id]) }}" > Unlike </a>

路线

 Route::get('product/{product}/unlike', ['as' => 'product.unlike', 'uses' => 'LikeController@destroy']);

点赞.php

  class Like extends Model
{
use SoftDeletes;

protected $table = 'likeables';

protected $fillable = [
    'user_id',
    'product_id',
    'likeable_id',
    'likeable_type',
];

public function products()
{
    return $this->morphedByMany('App\Product', 'likeable');
}

【问题讨论】:

  • 数据库中似乎没有具有给定 id 的产品。
  • @PaulSpiegel 数据库中有一个产品(4)
  • 查看Like模型中配置的表格!
  • 是的,我看到了 id 4 @PaulSpiegel
  • 如果你dd($product) 会有什么结果?

标签: php mysql laravel laravel-5


【解决方案1】:

删除请求应该是post request not get

web.php

Route::delete('product/{product}/unlike','LikeController@destroy')->name('product.unlike');

blade.php

<form action="{{ route('product.unlike',[$product->id]) }}" method="post">
 @csrf
 @method('DELETE')
 <button type="submit" class="remove"> Unlike </button>
</form>

controller

use App\Product;

...

public function destroy(Product $product) {
 $product->delete(); 
 return 'done'; 
}

希望这会有所帮助!

【讨论】:

  • 我收到了这个The DELETE method is not supported for this route. Supported methods: POST@Ben96
  • 是的,我已经尝试过了,我又收到了404 错误@Ben96
  • 公共函数销毁($product) { $product->delete();返回“完成”; }
  • 我得到Call to a member function delete() on string"@Ben96
  • 在 products 表中完全删除产品我想从另一个名为 likeables@Ben96 的表中删除产品
【解决方案2】:

拆下like对应的Products。

public function destroy($product)
{
    Like::where('product_id', $product)
         ->where('user_id', auth()->user()->id)
         ->delete();

    return 'done';
}

【讨论】:

  • 如果我使用这种方法,它会从产品表中的数据库中删除产品,我想删除另一个表(likeables)中的产品而不是产品表@linktoahref
  • 请分享您的Like 模型的架构。
  • 我得到了这个Column not found: 1054 Unknown column 'like_id' in 'where clause' (SQL: delete from likeables`` @linktoahref
【解决方案3】:

findOrFail 会抛出一个异常,当它找不到记录时会导致 404。您正在使用SoftDeletes,因此该记录可以存在于数据库中,但并不意味着它没有被“软删除”。如果它已被软删除,则范围将使它看起来不存在。

使用id == 4 检查您的记录,看看它是否有一个带有值的deleted_at 列。如果是,则将其删除(软删除)。您必须调整查询才能检索软删除的记录。

Laravel 6.x Docs - Eloquent - Soft Deletes - Querying Soft Deleted Models

【讨论】:

    猜你喜欢
    • 2016-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-02
    相关资源
    最近更新 更多