2016-04-14 117 views
0

我按標題顯示我的產品,有時我的某個產品的標題中會顯示一個「/」。每次點擊產品詳細信息時,都會給我一個錯誤,因爲URL中有一個斜線。所以我需要刪除斜槓,或在插入到後端數據庫之前顯示錯誤消息。如何在插入數據庫之前刪除斜槓「/」 - Laravel 5.2

這是我插入我的產品:(我使用的stripslashes,但它沒有做任何事情)

public function addPostProduct(ProductRequest $request) { 


     // Create the product in DB 
     $product = Product::create([ 
      'product_name' => stripslashes($request->input('product_name')), 
     ]); 


     // Save the product into the Database. 
     $product->save(); 

     // Flash a success message 
     flash()->success('Success', 'Product created successfully!'); 

     // Redirect back to Show all products page. 
     return redirect()->route('admin.product.show'); 
    } 

這是我的要求檢查:

class ProductRequest extends Request { 

    /** 
    * Determine if the user is authorized to make this request. 
    * 
    * @return bool 
    */ 
    public function authorize() 
    { 
     return true; 
    } 

    /** 
    * Get the validation rules that apply to the request. 
    * 
    * @return array 
    */ 
    public function rules() { 
     return [ 
      'product_name' => 'required|max:75|min:3|unique:products', 
     ]; 
    } 

} 

這是我按照標題顯示單個產品的途徑。 (我試過{!! !!},但它無法正常工作或)

<a href="{!! route('show.product', $product->product_name) !!}">Products Show</a> 
+0

使用' htmlspecialchars()'而不是'stripslashes()'。你也可以使用'urlencode()',但是如果你對這個名字進行比較,那麼這個問題就變成了不正確的解析路徑。也有辦法解決這個問題。 – Ohgodwhy

+0

「它給了我一個錯誤,因爲URL中有一個斜槓」http://php.net/manual/en/function.urlencode.php –

+0

它仍然插入數據庫的「/」 – David

回答

2

使用str_replace函數

$title = "product/124"; 

echo stripslashes($title) . "<br />"; 

echo str_replace("/", "", $title). "<br />"; 

或進一步澄清:

 $product_name = str_replace("/", "",$request->input('product_name')); 
// Create the product in DB 
     $product = Product::create([ 
      'product_name' => $product_name 
     ]); 
+0

yes thank you! – David