Laravel Eloquent relationship error - laravel-5

I'm using Laravel 5 for my blog. But when I use relation "hasMany", I got following error "FatalErrorException in 45abc28f0139bedaa1467307304d448ffaaed95e.php line 5: syntax error, unexpected '->' (T_OBJECT_OPERATOR) "
Here is my PostController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\View;
use App\Http\Requests;
use App\Post;
class PostController extends Controller
{
public function index(){
$listePosts = Post::all();
return view('post.index', compact('listePosts'));
}
public function show($detail){
$post = Post::where('detail', $detail)->firstOrFail();
$author = $post->user;
$comment = $post->comments;
return view('post.show', compact('post', 'author', 'comment'));
}
}
?>
Here is my Post Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $guarded = ['id', 'created_at'];
public function user(){
return $this->belongsTo('App\User');
}
public function comments(){
return $this->hasMany('App\Comment');
}
}
And here is my 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 $guarded = ['id', 'created_at'];
protected $fillable = [
'user_full_name', 'user_pseudo', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function posts(){
return $this->hasMany('App\Post');
}
public function comments(){
return $this->hasMany('App\Comment');
}
}
Please, how can I solve this problem ?
Thanks

here is my show.blade.php source code
#extends('template')
#section('content')
<div class="panel panel-primary">
<div class="panel-heading">
<h2 class="panel-title" align="center">{{post->post_name}}</h2>
<h3> Créé par : {{author->user_pseudo}} |
#if (post->count_comments == 0)
Pas de commentaire
#elseif (post->count_comments == 1)
1 Commentaire
#else
{{ post->count_comments}} Commentaires
#endif
</h3>
</div>
<div class="panel-body">
<p>{{post->content}}</p>
<div>
<h2 class="label label-info">Les commentaires</h2>
#foreach($comment as $oneComment)
<h4>Posté par : {{ $oneComment->user->user_pseudo}}</h4>
<p>{{ $oneComment->content}}</p>
#endforeach
</div>
</div>
</div>
#stop

Related

laravel 8 markdown email image not showing

I'm dispatching a markdown email using the Laravel's mailable class.
Here's the following code for the mailable.
<?php
namespace App\Mail;
use App\traits\Mail\RecordMailTrait;
use App\User;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Laravel\Spark\Invitation;
class ExistingUserCompanyInviteMail extends Mailable
{
use Queueable, SerializesModels, RecordMailTrait;
/**
* Create a new message instance.
*
* #return void
*/
protected $invite;
public $inviter;
public $view = 'email.invitation-to-current-user';
public function __construct(Invitation $invite, User $inviter)
{
$this->invite = $invite;
$this->inviter = $inviter;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
$invitation = $this->invite;
$view = $this->view;
$to = $this->to[0]['address'];
$sent_by_email = $this->inviter->email;
$this->withSwiftMessage(function ($message) use($invitation, $view, $to, $sent_by_email){
$message->view = $view;
$message->sent_to_email = $to;
$message->sent_by_email = $sent_by_email;
$message->mailable_type = Invitation::class;
$message->mailable_id = $invitation->id;
});
return $this->markdown($this->view,['invitation' => $this->invite, 'inviter' => $this->inviter, 'entity' => $this->invite->team->name, 'url' => url('/home/invitations')])->subject("Invitation");
}
}
I get the email in my inbox, with the correct text and styling, however not the image, it doesn't load as it should.
Here's the code for the HTML:
<tr>
<td class="header">
<a href="{{ $url }}" style="display: inline-block;">
<img src="{{ asset('/img/logo.svg')}}" class="logo" alt="logo1">
</a>
</td>
</tr>
This is the URL I get from the image in the sent email:
https://ci3.googleusercontent.com/proxy/8oh80_LJVyfK50ZObX23alnA8vhDzf3vXWJC_kHVgccnfzs-zSher-TbH9fO4RcDWjTQ5s8c_q3V6qc=s0-d-e1-ft#http://core-hosp.test/img/logo.svg
logo does not show (image of email)

Call to undefined method stdClass::isOnline() in Laravel 6

I'm trying to cheek the user is online or offline in my chat blade. I make a realtime chat in Laravel using Pusher and it's working fine but I have a issue to show user online offline status. I make middleware LastUserActivity and also registerd a my middleware in kernel.php but I constantly get this error.
Call to undefined method stdClass::save()
middleware
<?PHP
namespace App\Http\Middleware;
use Closure;
use Auth;
use Cache;
use Carbon\Carbon;
class LastUserActivity
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if(Auth::check()){
$expiresAt = Carbon::now()->addMinutes(1);
Cache::put('user-is-online-'.Auth::user()->id, true, $expiresAt);
}
return $next($request);
}
}
User Model
<?PHP
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Cache;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'gender', 'dob', 'image', 'password', 'is_admin', 'mobile', 'service_id', 'country_id', 'city_id', 'piincode'
];
/**
* 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',
];
//check if User is online
public function isOnline()
{
return Cache::has('user-is-online-'. $this->id);
}
}
my blade file is
<ul class="users">
#foreach($users as $user)
<li class="user" id="{{ $user->id }}">
{{--will show unread count notification--}}
#if($user->unread)
<span class="pending">{{ $user->unread }}</span>
#endif
<div class="media">
<div class="media-left">
<img src="{{ URL::asset('storage/uploads/vendor/'.$user->image) }}" alt="" class="media-object">
</div>
<div class="media-body">
<p class="name">{{ $user->name }}</p>
<p class="email">{{ $user->email }}</p>
#if ($user->isOnline())
<li class="text-success">Online</li>
#else
<li class="text-muted">Offline</li>
#endif
</div>
</div>
</li>
#endforeach
</ul>
my controller file is
<?PHP
namespace App\Http\Controllers;
use App\Message;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Pusher\Pusher;
class ChatsController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$users = DB::select("select users.id, users.name, users.image, users.email, count(is_read) as unread
from users LEFT JOIN messages ON users.id = messages.from and is_read = 0 and messages.to = " . Auth::id() . "
where users.id != " . Auth::id() . "
group by users.id, users.name, users.image, users.email");
return view('admin.chat', ['users' => $users]);
}
}
please help me. Thanks in advance
$users = DB::select("select users.id, users.name, users. ....
the $users will not hold a collection of user but a collection of std class ...
to hold a collection of users you should get the result using User Model ...
something like:
$users = User::selectRaw("users.id, users.name, users.image, users.email, count(is_read) as unread"
)->leftJoin('messages', 'users.id', 'messages.from')
->where('is_read', 0)->where('messages.to', Auth::id())
->where('users.id', '!=', Auth::id())
->groupBy(['users.id', 'users.name', 'users.image', 'users.email'])->get();

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.

Laravel, Undefined Variable in Views

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'] );

Laravel 5: Cannot access Eloquent relationship data

After trying out every solution I found on Google, I still cannot seem to access my relationship's data. I keep getting the following error:
Trying to get property of non-object (View: /home/eneko/foundry/biome/resources/views/home.blade.php)
Here are the files that load for this route:
Fruitu.php
<?php namespace Biome;
use Illuminate\Database\Eloquent\Model;
use Cviebrock\EloquentSluggable\SluggableInterface;
use Cviebrock\EloquentSluggable\SluggableTrait;
class Fruitu extends Model implements SluggableInterface {
use SluggableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'fruitus';
public function toString() {
return $this->izenburua;
}
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['izenburua', 'irudia', 'edukia'];
public function egilea() {
return $this->belongsTo('Biome\User');
}
protected $sluggable = array(
'build_from' => 'izenburua',
'save_to' => 'slug',
);
}
The controller function:
public function index()
{
$fruituak = Fruitu::all();
$fruituak->load('egilea');
return view('home')->with(compact('fruituak'));
}
The loop in the blade template:
#foreach ($fruituak as $fruitu)
<div class="fruitua">
<a href="{{ route('fruitu.show', $fruitu->slug) }}">
<h3>{{ $fruitu->izenburua }}</h3>
</a>
{{ $fruitu->egilea->name }}
<p class="eduk">{{ $fruitu->edukia }}</p>
</div>
#endforeach
Thanks in advance for your help!

Resources