Trying to get property of non-object laravel?

3.3k Views Asked by At

I am a beginner. I'm trying to fix, i think i need help.

-This is code Controller

         if(Input::hasFile('image')){

            $dest = 'media/images/product/';

            $name = str_random(6).'_'.Input::file('image')->getClientOriginalName();

            //$resize = 
            Input::file('image')->move($dest,$name);
        }

        $loaispname = Input::get('loaispname');

        $loaisp = new Loaisp;


        $datas = $loaisp->getidloaisp($loaispname);

        $idloaisp = $datas->id;

        $item = new Sanpham;
        $item->loaisp_id = $idloaisp;
        $item->sanpham_name = Input::get('sanpham');
        $item->sanpham_img = $name;
        $item->sanpham_tieude = Input::get('tieude');
        $item->sanpham_gia = Input::get('gia');
        $item->sanpham_chitiet = Input::get('chitiet');
        $item->sanpham_vitri = Input::get('vitri');
        $item->save();

        return Redirect::to('admin/dsachsanpham')->with('thanhcong','Saved');

-This is code Model

    public function getidloaisp($loaispname){

        //return Loaisp::where('loaisp_name','=',$loaispname)->get();
        return DB::table('loaisp')->where('loaisp_name',$loaispname)->first();
    }

-this is Error

ErrorException (E_UNKNOWN) Trying to get property of non-object Open: E:\xampp\htdocs\www\daunhot\app\controllers\AdminController.php

        $loaispname = Input::get('loaispname');

        $loaisp = new Loaisp;


        $datas = $loaisp->getidloaisp($loaispname);

        $idloaisp = $datas->id; // This is error

        $item = new Sanpham;
4

There are 4 best solutions below

0
On

When you see this error there could be two error: You got nothing back with your query(DB::table('loaisp')->where('loaisp_name',$loaispname)->first();), Or you got back an array, if you are using ->get() instead of ->first() you will get this error. Try to use a foreach on your query result, or try to use dd() function on your result so you can see if is empty or not. If it is empty that is your porblem.

0
On

Same as what the rest is saying, dump $datas before the error, maybe add '=' to your where clause in that 'getidloaisp' function. You should be able to use the one your quoted out though, that is if you change the '->get()' to '->first()'.

0
On

$datas->id work with DB table is need to be the table datas and cell id, and also they are case sensitive, not use Id or other.

0
On

Check if you are getting 'loaispname' on Input::get by:

echo "<pre>";
print_r($loaispname);
echo "</pre>";
exit;

If you're getting your posted data then do:

echo "<pre>";
print_r($datas);
echo "</pre>";
exit;