Laravel 5.4 Model::where not working - php

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

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 );
}

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

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.

Related

parameter passed to relationship from controller to model in laravel but not working

in my controller parameter passed to posts function in user model with construct method .
class MyController extends Controller
{
private $user;
public function __construct(User $getuser)
{
$this->user = $getuser;
}
public function index($id = 2)
{
$posts = $this->user->posts($id);
$user = User::FindOrFail($id);
return $user->posts;
}
}
in my user model parameter accessed and passed to relationship .
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'email', 'password',
];
function posts($id)
{
return $this->hasMany('App\Post')->where('id',$id);
}
}
it works when use like this
"return $this->hasMany('App\Post')->where('id',1);"
but not working with passed parameter. getting this error
"Symfony\Component\Debug\Exception\FatalThrowableError Too few
arguments to function App\User::posts(), 0 passed in
C:\xampp\htdocs\blog\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\HasAttributes.php
on line 415 and exactly 1 expected"
Check your controller method you should be returning. ie: return $posts instead of return $user->posts as this is seeking to find posts without passing in the id as you do with $posts = $this->user->posts($id);
That's why you are getting a symphony error of too few arguments as you pass no arguments in return $user->posts
User Model
function posts($id)
{
return $this->hasMany('App\Post');
}
You could access the post with the given condition by using where on the relation method.
Querying relations
https://laravel.com/docs/7.x/eloquent-relationships#querying-relations
$post = $user->posts()->where('id', $id)->first();
You could use get() or first() according to your requirement.
$posts = $user->posts()->where('id', $id)->get();
If you want a user who has a post that satisfies the criteria.
$user = User::whereHas('posts', function($query) use($id){
$query->where('id', $id);
// You may add several other conditions as well.
})
->with(['posts' => function($query) use($id){
$query->where('id', $id);
}
])
->first();
Now,
$user->posts
will give a collection of only ONE post Model Instance that satisfied the condition

Laravel - Request Null

I'm trying to request the $year off my form in my show method but it's returning null. I'm logging time entries and I want to query the times by years like this: $times = Time::where('user_id', $id)->whereYear('start_day', $request->year)->get();. This query works inside of my getReports method, but not in my show method which Is where I want it to work. If I dd($request->all()) inside of my show method It just returns an empty array. I'm not sure how to fix this, I believe it has to do with my route getReport. Is there a way to pass those values into the show method? I just need the $request->year to work so I can query properly.
Routes:
Route::resource('admin/reports', 'Admin\ReportController', [ 'as' => 'admin'])->middleware('admin');
Route::post('admin/reports/getReport', 'Admin\ReportController#getReport')->name('admin.getReport')->middleware('admin');
Form POST:
<form method="POST" action="{{ route('admin.getReport') }}">
Controller:
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Helper\ReportHelper;
use App\Time;
use App\User;
use App\Category;
use App\Offtime;
use Carbon\Carbon;
use Auth;
use Date;
use PDF;
use Session;
class ReportController extends Controller
{
public function create() {
$users = User::all();
$times = Time::all();
$years = array();
$length_times = count($times);
for($i=0;$i<$length_times;$i++){
$year = Carbon::parse($times[$i]->start_day)->format('Y');
array_push($years, $year);
}
$years = array_unique($years);
return view('admin.report.create', compact('users', 'years'));
}
public function show($id, Request $request) {
$user = User::find($id);
if (!$user) {
return false;
}
$times = Time::where('user_id', $id)->get();
return view ('admin.report.show', compact('user','times')
}
public function getReport(Request $request) {
$form_user = $request->form_user;
$year = $request->year;
if (!$form_user) {
return abort(404);
}
$user = User::find($form_user);
if ($user) {
return redirect()->route('admin.reports.show', $user->id);
}
return abort(404);
}
}
For default show uses GET method and you are trying to make a POST.
getReport you defined as post, that's why it's working.
More information about route resource
https://laravel.com/docs/5.7/controllers
In this case, I prefer to use Route Model Binding
public function show(User $user) {
$times = Time::where('user_id', $user->id)->get();
return view ('admin.report.show', compact('user','times')
}
This will handel if the user does not exist.

Filtering data with spatie query builder using trait

I put logic from my function index() of UserController in trait taht i created:
public function index()
{
$this->authorize('view', Auth::user());
$users = QueryBuilder::for(User::class)
->allowedIncludes('kids','roles','articles','recordings')
->allowedFilters('first_name', 'last_name', 'email')
->get();
return UserResource::collection($users);
}
and this is my trait :
<?php
namespace App\Http\Traits;
use App\Models\User;
use Spatie\QueryBuilder\QueryBuilder;
trait Filterable
{
public function filter()
{
$users = QueryBuilder::for(User::class)
->allowedIncludes('kids','roles','articles','recordings')
->allowedFilters('first_name', 'last_name', 'email')
->get();
return $users;
}
}
So now my function index() looks like this:
use Filterable;
public function index()
{
$this->authorize('view', Auth::user());
$users = $this->filter();
return UserResource::collection($users);
Now when i do this in my postman
{{url}}/api/users?filter[first_name]=anna
it works and it returns anna from my database but when I try
{{url}}/api/users?include=roles
it return every user from database but does not include roles.
Can somebody help me with this?
This is taken straight from the github page: https://github.com/spatie/laravel-query-builder#custom-filters
Custom filters
use Spatie\QueryBuilder\Filters\Filter;
use Illuminate\Database\Eloquent\Builder;
class FiltersUserPermission implements Filter
{
public function __invoke(Builder $query, $value, string $property) : Builder
{
return $query->whereHas('permissions', function (Builder $query) use ($value) {
$query->where('name', $value);
});
}
}
use Spatie\QueryBuilder\Filter;
// GET /users?filter[permission]=createPosts
$users = QueryBuilder::for(User::class)
->allowedFilters(Filter::custom('permission', FiltersUserPermission::class))
->get();
// $users will contain all users that have the `createPosts` permission

Laravel 5.1 Call to undefined method Illuminate\Database\Query\Builder::cartItems()

I have the following model and controller but it keeps throwing error:
Call to undefined method Illuminate\Database\Query\Builder::cartItems()
This is my model and controller:
class Cart extends Model
{
protected $fillable = [
'user_id',
'coupon_id',
];
public function cartItems()
{
return $this->hasMany('App\CartItem');
}
}
use App\Cart;
use App\CartItem;
class CartController extends Controller
{
public function index()
{
$userId = Auth::user()->id;
$cart = Cart::where('user_id', '=', $userId);
$cartItems = $cart->cartItems()->get();
//...some other stuff...
return view('cart.index', compact('cartItems'));
}
}
Don't call it as a function:
$cart = Cart::where('user_id', '=', $userId)->first();
$cartItems = $cart->cartItems;
Laravel will take care of the rest, and get the items from the database.

Not Able to get Auth::user->id in Laravel

Here is my Controller.
<?php
/**
* Created by PhpStorm.
* User: ed
* Date: 05/02/16
* Time: 09:33
*/
namespace App\Http\Controllers\API\V1;
use App\Certificate;
use App\Country;
use App\Film;
use App\FilmExtra;
use App\FilmFavourite;
use App\FilmGenre;
use App\FilmLike;
use App\FilmView;
use App\Genre;
use App\Language;
use App\Magazine;
use App\News;
use App\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
class MagazineController extends ApiController
{
public function viewAll(){
echo Auth::user()->id;
exit;
$user_id = Input::get('user_id');
$magazines = Magazine::paginate(5);
return parent::api_response($magazines->toArray(), true, ['return' => 'all magazines'], 200);
}
public function getMagazine($id){
$magazine = Magazine::find($id);
if($magazine){
return parent::api_response($magazine->toArray(), true, ['return' => 'magazine details'], 200);
}else{
return parent::api_response([], false, ['error' => 'Couldn\'t find that magazine'], 404);
}
}
protected function getURL($id){
$magazine = Magazine::find($id);
if($magazine){
return parent::api_response(['url' => $magazine->file_url], true, ['return' => 'magazine url'], 200);
}else{
return parent::api_response([], false, ['error' => 'Couldn\'t find that magazine'], 404);
}
}
public function search($term){
$magazines = Magazine::search($term)->paginate(5);
return parent::api_response($magazines, true, ['return' => 'search for '.$term], 200);
}
public function purchased(){
$magazines = Magazine::leftJoin('ordered_items', 'ordered_items.item_id', '=', 'magazines.id')
->leftJoin('orders', 'orders.id', '=', 'ordered_items.order_id')
->leftJoin('items', 'items.id', '=', 'ordered_items.item_id')
->where('orders.user_id', $user_id)
->where('items.class', 'book');
if(Input::get('filter')) {
$jsonFilter = Input::get('filter');
$filters = json_decode($jsonFilter);
foreach ($filters as $filter => $value){
switch ($filter){
case "genre":
if($value){
$magazines = $magazines->whereHas('genre', function ($query) use($value) {
$query->whereIn('genre_id', $value);
});
}
break;
case "cert":
if($value){
$magazines = $magazines->whereIn('cert', $value);
}
break;
case "country":
if($value){
$magazines = $magazines->whereIn('country', $value);
}
break;
case "lang":
if($value){
$magazines = $magazines->whereHas('languages', function ($query) use($value) {
$query->whereIn('language_id', $value);
});
}
break;
}
}
}
$magazines = $magazines->paginate(5);
return parent::api_response($magazines->toArray(), true, ['return' => 'all magazines'], 200);
}
}
If i call any of the function for this controller i am not able to get my Auth::user()->id.
it's throwing an error.
ErrorException in MagazineController.php line 54:
Trying to get property of non-object
If i try to echo Auth::user()->id in any other controller, its working fine.
using laravel 5.2
Can anybody help me ?
don't hesitate to ask any question if you want.
Probably the Auth::user returns nulland you are trying to get id of null.
So make sure that user is logged like:
if (Auth::check()) {
// The user is logged in...
echo Auth::user()->id;
}
Ensure your routes for this controller are wrapped in the web middleware group.
Also, since MagazineController extends ApiController, ensure that ApiController extends Controller.
Use it like this the Laravel 5.2 way
$user_collection = Auth::user();
echo $user_collection->id;
exit;
Did you changed the id name of your users table? I experienced that. I made mine all capital (ID). I was on Linux and db, table, and column names are case sensitive. Try checking the id column of your users table.
That is, if you're sure that the user is logged in. Else, it would be null if I'm not mistaken.
Put your controller under a login Middleware to ensure you have a logged in user, or simply put a verification before you access user id:
if (Auth::check()) {
$id = Auth::user()->id;
}
What ApiController do?
Change the namespace at the top to
namespace App\Http\Controllers;
Try to change ApiController with plain Controller and check what will be happen
Instead of:
class MagazineController extends ApiController
Change it like so:
class MagazineController extends Controller

Categories