Laravel, Undefined Variable in Views - laravel-5

I tried to work on my problem but i'm stuck here can't resolve why the variable is undefined in home.blade.php This is my HomeController.php where i have $items variable which is causing problem
<?php
use app\Item;
namespace App\Http\Controllers;
class HomeController extends BaseController
{
public function __construct(Item $items)
{
$this->items = $items;
}
public function getIndex()
{
$items = Auth::user()->items;
return View::make('home', array(
'items' => $items
));
}
public function postIndex()
{
$id = Input::get('id');
$useId = Auth::user()->id;
$item = Item::findOrFail($id);
if($item->owner_id == $userId)
$item -> mark();
return Redirect::route('home');
}
}
?>
and this is Items class where i have extended it with eloquent
<?php
class Item extends Eloquent
{
public function mark()
{
$this->done = $this->done?false:true;
$this->save();
}
}
while i have another function of items which i'm trying to use as a variable in view this is file of user.php and function is defined at the end
<?php
namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['name', 'email', 'password'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
public function items()
{
return $this->hasMany('Item','owner_id');
}
}
And this is the file from views home.blade.php where its giving error on foreach loop
Error: ErrorException in b5a9f5fc2ee329af8de0b5c94fd30f78 line 7:
Undefined variable: items (View: C:\Users\Rehman_\Desktop\todo-application\resources\views\home.blade.php)
#extends('master')
#section('content')
<h1>TO DO: Items</h1>
<hr>
<ul>
#foreach ($items as $item)
#endforeach
</ul>
#stop
Update: Route.php file
<?php
Route::get('/',array('as'=>'home','uses'=>'PageController#getindex'))->before('auth');
Route::post('/',array('uses','HomeController#postIndex'))->before('csrf');
Route::get('/login',array('as'=>'login','uses' => 'Auth\AuthController#getLogin'))->before('guest');
Route::post('login',array('uses' => 'Auth\AuthController#postLogin'))->before('csrf');

Try this:
return View('home', compact('items'));
Instead of this:
return View::make('home', array(
'items' => $items
));

Your route is probably pointing to the wrong controller/method hence the variable is not been sent to the view.
Try:
Route::get('/', [ 'as'=>'home','uses'=>'HomeController#getIndex'] );

Related

How to use eloquent on the auth command user in laravel

I am facing a weird error right now
In my controller, when I import the class user like this
use Illuminate\Foundation\Auth\User;
It works when I use eloquent like
public function index()
{
$farms = User::where('role_id', 3)->get();
$user = Auth::user();
$animal = Animal::all();
return view('clinic.index', compact('user', 'animal', 'farms'));
}
But refuses to work when it comes to table relationships like
public function show($id)
{
$farms = User::with(['animals'])->findOrFail($id);
return view('clinic.show',compact('farms'));
}
showing me this error
"Call to undefined relationship [animals] on model [Illuminate\Foundation\Auth\User]"
But whenever I import the user class as App\User in my controller,
It works in the relationship but refuses to work with the eloquent showing this error
"Call to a member function get() on null"
Now I am kinda confused. Any help will be welcomed
App\User
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $guarded = [];
public static function where(string $string, int $int)
{
}
public static function select(array $array)
{
}
public function role(){
return $this->belongsTo(Role::class);
}
public function animals(){
return $this->hasMany(Animal::class);
}
public function clinics(){
return $this->hasMany(Clinic::class);
}
public function slaughter(){
return $this->hasMany(Slaughter::class);
}
public function address(){
return $this->belongsTo(Address::class);
}
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
The Illuminate\Foundation\Auth\User class is the parent of the App\User class and animals relation set in the App\Userclass. So you can't call animals relation from Illuminate\Foundation\Auth\User class.
You should remove these functions from the App\User Model:
public static function where(string $string, int $int)
{
}
public static function select(array $array)
{
}

Laravel 5.3 ErrorException in Model.php line 2709

I am using Laravel 5.3 and I want to send verification mail using the following
php artisen make:auth
php artisen make:mail ConfirmationEmail
ConfirmationEmail.php
<?php
namespace App\Mail;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class ConfirmationEmail extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* #return void
*/
public $user;
public function __construct(User $user)
{
$this->user = $user;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->view('emails.confirmation');
}
}
emails/confirmation.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sign Up Confirmation</title>
</head>
<body>
<h1>Thanks for signing up!</h1>
<p>
We just need you to <a href='{{ url("register/confirm/{$user->token}") }}'>confirm your email address</a> real quick!
</p>
</body>
</html>
UserController.php
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email|unique:users',
'name' => 'required|string',
'password' => 'required|string|min:6',
'country' => 'required'
]);
if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()], 401);
}
$input = $request->all();
$input['password'] = bcrypt($input['password']);
$input['user_pin'] = $this->generatePIN();
$user = User::create($input);
Mail::to($user->email)->send(new ConfirmationEmail($user));
$success['token'] = $user->createToken('MyApp')->accessToken;
$success['user'] = $user ;
$now = Carbon::now();
UserLocation::create(['user_pin' => $input['user_pin'] , 'lat'=> 0.0 , 'lng' => 0.0 , 'located_at' => $now]);
return response()->json(['success'=>$success], $this->successStatus);
}
Models/User.php
<?php
vnamespace App\Models;
use App\User as BaseUser;
class User extends BaseUser
{
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function groups(){
return $this->belongsToMany(Group::class, 'group_member', 'member_id', 'group_id');
}
public function sentRequests(){
return $this->hasMany(Request::class, 'from_user_pin', 'user_pin');
}
public function receivedRequests(){
return $this->hasMany(Request::class, 'to_user_pin', 'user_pin');
}
public function locations(){
return $this->hasMany(UserLocation::class, 'user_pin', 'user_pin');
}
}
App\User.php
<?php
namespace App;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
protected $guarded = ['id'];
/**
* The attributes that are mass assignable.
*
* #var array
*/
/*protected $fillable = [
'name', 'email', 'password',
];*/
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
I am now getting this error
ErrorException in Model.php line 2709:
Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation (View: /var/www/html/group_map_v1/resources/views/emails/confirmation.blade.php)
token is a method on the model. When you try to access the dynamic property on the model, it looks for an attribute then for relationship method (or already loaded relationship) by that name.
You have no attribute named token. When you try to access it via the dynamic property it looks for a method named token (this is how it can access relationships via that property). When it does this it hits that method and that method does not return a relationship type object. So Eloquent breaks at that point as that property is for attributes and relationships, and it can't do anything with it.
asklagbox - blog - eloquent misunderstandings - dynamic properties and relationships
You're getting this error, you're trying to use a model method as a relationship, but this method doesn't return one. The relationship should look like this:
public function relationship()
{
return $this->hasMany(Model::class);
}
Update
HasApiTokens trait has a method named token() which is a simple accessor:
public function token()
{
return $this->accessToken;
}
When you do $user->token, Laravel sees this method and trying to use it as a relationship.
So, what you want to do is to rename your token property in the users table to something else.
Thanks to #lagbox for the pointing in the right direction.

Laravel relationships not working as expected

So I have been building this simple Guest book where people leave comments. Ive linked the user model to the comment model and have tried returning the user that posted the comment however I always get an error. Ive made a Ticketing program before this using the same code and it worked and works fine still. See below
Comment Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function user()
{
return $this->belongsTo('User::class');
}
}
User Model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function comments()
{
return $this->hasMany(Comment::class);
}
}
And this is the controller where I am trying to return the results
<?php
namespace App\Http\Controllers;
use App\Comment;
use App\User;
use Auth;
use Illuminate\Http\Request;
class HomeController extends Controller
{
public function index()
{
$comments = Comment::all();
$user = Auth::user();
$test = User::all();
$average = number_format((Comment::avg('rating')),2, '.', '');
dd($comments->user);
return view('welcome')->withComments($comments)->withUser($user)->withAverage($average);
}
}
Everytime I try and DD the result I get the error
Property [user] does not exist on this collection instance.
I am 100% stumped why this will work on one project and not another. I even rebuilt this little app to see if it was something I had done and I still get the same result.
You're trying to get property of a collection, not an object. So do this:
foreach ($comments as $comment) {
dump($comment->user); // $comment is an object
}

Session of logged user return undefined

I have custom login function in Laravel 5.4 which seems to work but not exactly. What I have in UserController.php is
public function loginSubmit()
{
$user = User::where('username', Input::get('username'))->first();
if (!$user) {
$validator->messages()->add('username', 'Invalid login or password.');
return Redirect::to('/users/login')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
}
if (!Hash::check(Input::get('password'), $user->password)) {
$validator->messages()->add('username', 'Invalid login or password.');
return Redirect::to('/users/login')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
}
$user->last_login = \Carbon\Carbon::now();
$user->save();
Session::put('user', ['user_id' => $user->user_id]);
//dd(Session::get('user', null));
return Redirect::to('/');
}
dd(Session::get('user', null)); return
array:1 [▼
"user_id" => 1
]
Which means that user with ID=1 is logged and is in stored in session. In BaseController.php which sharing the user session I have this
public static function isLoggedIn()
{
$user = Session::get('user', null);
if ($user !== null) {
return true;
} else {
return false;
}
}
But when I tried to show the username of the logged in user
{{ $user->username }}
I've got error
Undefined variable: user
This my Users model
namespace App;
use Illuminate\Database\Eloquent\Model;
use Eloquent;
use DB;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Eloquent implements AuthenticatableContract, CanResetPasswordContract
{
use Authenticatable, CanResetPassword;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password');
protected $primaryKey = 'user_id';
}
Any idea what is wrong with my session here?
It means that $user is not defined in the blade file you are using.
Call the view with the user as a parameter (i think this is the best approach):
$user = Session::get('user', null);
return view('yourview')->with(['user' => $user];
Or use the Session in your blade file:
{{ Session::get('user', null)->username }}
EDIT: to use View::share. You can put this inside the boot function of your Service provider:
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
$user = Session::get('user', null);
View::share('user', $user);
}
//...
}

Undefined variable: currentUser

I was following the laracasts video for creating follow option but on clicking on the username it is showing the above error and I don't know where to define this variable. Followscontroller
<?php
namespace App\Http\Controllers;
use Redirect;
use App\User;
use Laracasts\Commander\CommanderTrait;
use App\FollowUserCommand;
use Sentinel;
use Illuminate\Support\Facades\Input;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class FollowsController extends Controller
{
use CommanderTrait;
/**
* Follow a User
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store()
{
$input = array_add(Input::all(), 'user_id', Sentinel::getuser()->id);
$this->execute(FollowUserCommand::class, $input);
return Redirect::back();
}
/**
* Unfollow a User
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
FollowUserCommand
<?php namespace App;
use App\User;
class FollowUserCommand {
public $user_id;
public $userIdToFollow;
function __construct($user_id, $userIdToFollow)
{
$this->user_id = $user_id;
$this->userIdToFollow = $userIdToFollow;
}
}
FollowUserCommandHandler
<?php namespace App;
use Laracasts\Commander\CommandHandler;
class FollowUserCommandHandler implements CommandHandler {
protected $userRepo;
function __construct(UserRepository $userRepo)
{
$this->userRepo = $userRepo;
}
public function handle($command)
{
$user = $this->userRepo->findById($command->user_id);
$this->userRepo->follow($command->userIdToFollow, $user);
return $user;
}
}
UserRepository
<?php namespace App;
use App\User;
class UserRepository {
public function save(User $user)
{
return $user->save();
}
public function getPaginated($howMany = 4)
{
return User::orderBy('first_name', 'asc')->paginate($howMany);
}
public function findByUsername($username)
{
return User::with(['feeds' => function($query)
{
$query->latest();
}
])->whereUsername($username)->first();
}
public function findById($id)
{
return User::findOrFail($id);
}
public function follow($userIdToFollow, User $user)
{
return $user->follows()->attach($userIdToFollow);
}
}
User.php
<?php namespace App;
use Cartalyst\Sentinel\Users\EloquentUser;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends EloquentUser {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes to be fillable from the model.
*
* A dirty hack to allow fields to be fillable by calling empty fillable array
*
* #var array
*/
protected $fillable = [];
protected $guarded = ['id'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
/**
* To allow soft deletes
*/
use SoftDeletes;
protected $dates = ['deleted_at'];
public function feeds()
{
return $this->hasMany('App\Feed');
}
public function comment()
{
return $this->hasMany('App\Comment');
}
// This function allows us to get a list of users following us
public function follows()
{
return $this->belongsToMany(self::class, 'follows', 'follower_id', 'followed_id')->withTimestamps();
}
// Get all users we are following
public function following()
{
return $this->belongsToMany('User', 'followers', 'user_id', 'follow_id')->withTimestamps();
}
// if current user follows another user
public function isFollowedBy(User $otherUser)
{
$idsWhoOtherUserFollows = $otherUser->follows()->lists('followed_id');
return in_array($this->id, $idsWhoOtherUserFollows) ;
}
}
form.blade.php
#if($user->isFollowedBy($currentUser))
<p>You are following {{ $user->username }}<p>
#else
{!! Form::open(['route' => 'follows_path']) !!}
{!! Form::hidden('userIdToFollow', $user->id) !!}
<button type="submit" class="btn btn-primary">Follow {{ $user->username }} </button>
{!! Form::close() !!}
#endif
Assuming the tutorial implements the Auth class, you can get the current user by changing #if($user->isFollowedBy($currentUser)) to #if($user->isFollowedBy(\Illuminate\Support\Facades\Auth::user())). It is otherwise very difficult to read through your code, but kudos to you for trying to be thorough.
You obviously don't want to use Auth::user() in this way. Trying using it as Auth::user() without the full namespace, but otherwise add the namespace as use Illuminate\Support\Facades\Auth; in the controller handling that view.

Resources