user2496181
user2496181

Reputation: 11

Laravel 5.4 Model::where not working

I'm a bit new to laravel and try to do a simple thing, just trying to select multiple rows with eloquent and tried :

<?php

namespace App\Http\Controllers;
use Auth;
use App\Company;
use App\User;
use Illuminate\Support\Facades\View;
use Model;

class BaseController extends Controller {


    public function __construct() {

            //$companies = Company::find(1);
            //$companies = Company::all();
            $companies = Company::where('owner_id', Auth::user()->id);
                print_r($cpm);
            View::share ( 'companies', '$companies' );
    }

}

But always get this error :

ErrorException

Trying to get property of non-object in BaseController.php (line 16)

And 2 commented lines above are working fine, so i'm a bit lost?

Thanks,

Nicolas

Upvotes: 1

Views: 769

Answers (3)

Ron van der Heijden
Ron van der Heijden

Reputation: 15070

You are trying to get the ID of a loggedin user when no user is logged in. So you should check if a user is logged.

I advice you to use a middleware.

You can also check if the user is logged in using:

if (Auth::check()) {
    $companies = Company::where('owner_id', Auth::user()->id)->get();
}

Read this for more information about Authentication: https://laravel.com/docs/5.6/authentication

Upvotes: 1

SystemGlitch
SystemGlitch

Reputation: 2262

The where() method returns a Builder object and not the result of the query. You need to call get() method in order to get an exploitable Collection.

Upvotes: 0

Techno
Techno

Reputation: 1696

public function __construct() {

        //$companies = Company::find(1);
        //$companies = Company::all();
        $companies = Company::where('owner_id', Auth::user()->id);
            print_r($cpm);
        View::share ( 'companies', '$companies' );
}

This piece:

$companies = Company::where('owner_id', Auth::user()->id);

Needs to change into this:

 $companies = Company::where('owner_id', Auth::user()->id)->get();

The get makes sure your sql gets runned, and the output us returned to $companies.

And I believe

 View::share ( 'companies', '$companies' );

needs to be:

 View::share ( 'companies', $companies );

resulting in:

public function __construct() {

        //$companies = Company::find(1);
        //$companies = Company::all();
        $companies = Company::where('owner_id', Auth::user()->id)->get();
            print_r($cpm);
        View::share ( 'companies', $companies );
}

Upvotes: 2

Related Questions