0

My model:

class Product extends Model
{
    protected $table = 'Products';
    protected $fillable = ['product-code', 'type', 'name', 'description', 'price', 'discount', 'image', 'image_alt'];

    public function products()
    {
        return $this->hasMany('App\ProductSpecifics');
    }
}

Controller:

public function find_product(Request $request)
{
    $this->validate($request, [
        'code' => 'required|max:50|string'
    ]);
    $Product = Product::where('product-code', '=', $request->get('code'))->first();
    if(strlen($Product->name > 0))
    {
        return view('edit_product', compact('Product'));
    }
    return redirect()->route('edit_product')->with('fail', 'Failed to find the product.');
}

Form:

            <form action="{{route('find_product')}}" method="post">
                <div class="form-group">
                    <label for="name" class="control-label">Product Code</label>
                    <input class="form-control" name="code" id="product_code" type="text" placeholder="Enter product code...">
                </div>
                @error('code')
                <div class="alert alert-danger">{{ $message }}</div>
                @enderror
                <div class="form-group">
                    <button type="submit" class="btn btn-primary float-lg-right">Search for product</button>
                </div>
                {{ csrf_field() }}
            </form>

Whenever I submit the form, I get "Trying to get property 'name' of non-object", what am I doing wrong? I do have the App/Product included in my controller.

EDIT: Adding "dd($Product);" to my controller provides me with "null" as the answer.

Just Another Guy
  • 77
  • 1
  • 2
  • 9

1 Answers1

0

To answer your question.

$product = Product::where('product-code', $request->get('code'))->first(); // remove '='
if($product) // if the product with given code is not found then the $product would be null
{
    return view('edit_product', compact('product'));
}
return redirect()->route('edit_product')->with('fail', 'Failed to find the product.');

There are still many coding standard issues in your code. I recommend going through Laravel Best Pratices.

Digvijay
  • 7,836
  • 3
  • 32
  • 53