Method Illuminate\Auth\SessionGuard::users does not exist in Laravel - laravel

I am trying to attach the roles, users, and users_role tables. Trying to connect them and checking on the Blade file that if a user's role is admin, he can only access the user's route; otherwise, he can't access it. For other users, the users' route must not be seen. At the same time, verifying code on the Blade file throws an error. How can I solve this in the latest Laravel 8?
app.blade.php
#if(Auth::users()->roles()->where('name', 'Admin')->exists())
<li class="nav-item">
<a class="nav-link" href="{{ url('/Admin/users')}}">Users</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ url('/Admin/Posts')}}">Posts</a>
</li>
#else
<li class="nav-item">
<a class="nav-link" href="{{ url('/Admin/Posts')}}">Posts</a>
</li>
#endif
Role model
public function users()
{
return $this->belongsToMany(User::class, 'users_roles', 'user_id', 'role_id')
->using(UserRole::class);
}
User model
public function roles()
{
return $this->belongsToMany(role::class, 'users_roles', 'role_id',
'user_id')->using(UserRole::class)->withPivot('name');
}
Error

Simply Replace this
#if(Auth::users()->roles()->where('name', 'Admin')->exists())
Into
#if(\Auth::user()->roles =='Admin')
I hope you got your solution .

with the help of rakesh answer https://stackoverflow.com/a/68176136/16114539
and some modification , the error got solved ..
so you can check the current user and check role of it and then show it the code is like:
#if(Auth::check() && Auth::user()->roles()->where('name', 'Admin')->exists())
it get solved

Related

Laravel calling controller function from blade file not working

I have a Laravel project where I'm trying to call a controller function from blade file called nav.blade.php, but I'm getting following error:
syntax error, unexpected fully qualified name
"\App\Http\Controllers\ProductC...", expecting ":".
nav.blade.php
{{ use \App\Http\Controllers\ProductController; }}
<div class="container">
<ul class="navbar-nav mr-auto">
{{ $is_admin = ProductController::isAdmin(); }}
#if($is_admin == "admin")
<li class="nav-item">
<a class="nav-link" href="/posts">Admin</a>
</li>
#endif
</ul>
</div>
ProductsController.php
public static function isAdmin()
{
$user_id = Auth::id();
$user = User::findOrFail($user_id);
$is_admin = $user->role;
if($is_admin==="admin"){
return "admin";
}elseif($is_admin==="moderator"){
return "moderator";
}else{
return "user";
}
}
You access the static controller function from the blade template.
<?php
$isAdmin= App\Http\Controllers\ProductController::isAdmin();
?>
{{ }} are used to echo anything you want. If you want to import a class, one solution is to do like the following:
<?php
use \App\Http\Controllers\ProductController;
$is_admin = ProductController::isAdmin();
?>
<div class="container">
<ul class="navbar-nav mr-auto">
#if($is_admin == "admin")
<li class="nav-item">
<a class="nav-link" href="/posts">Admin</a>
</li>
#endif
</ul>
</div>
But this isn't a best practice I recommend you to move isAdmin() method from ProductController and set it as global function of your system so you can directly access it from your view without importing a controller.
Never EVER use a controller in a Blade. That is not good in any way and would require me a lot of explanation that is already in some blogs...
A controller is ONLY used for accessing something through a URL, do something and done, it is not a Service class where you do business logic anywhere you want.
So, move that method to a Service class (do not confuse with Service Provider) and use it in the blade. It would still be better to pass that variable to the view and not using any class just for that...

Laravel vue: I can't get the object related to the relationship betwenn models

I've created a simple comment system. Everything's working fine. Now I had to create the same approach with Vue.js. Everything works well with Vue.j too. The only problem is that I can't show the answers related to the comment using the relationship.
I show first the relationship code, then the PHP loop and finally the loop code with Vue.js
//USER MODEL
public function comments()
{
return $this->hasMany(Comment::class,'user_id');
}
//COMMENT MODEL
public function video()
{
return $this->belongsTo(Video::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
public function replies()
{
return $this->hasMany(CommentReply::class,'comment_id');
}
//CommentReply model
public function comment()
{
return $this->belongsTo(Comment::class);
}
This is the loop
#foreach( $video->comments as $comment )
<li id="li-comment-5">
<article class="comment even thread-odd thread-alt depth-1 clr" id="comment-5">
<header class="comment-meta"> <strong class="fn"> {{ $comment->user->name }}
</strong> <span class="comment-date">July 4, 2017 7:25 am </span></header>
<div class="comment-content entry clr">
<p>{{ $comment-body}}</p>
</div>
<h5>Reply</h5>
#foreach($comment->replies as $reply)
$reply->body
#enddoreach
</div>
</article>
</li>
#endforeach
Loop with Vue
<ol class="commentlist" v-if="comments.length > 0">
<li id="li-comment-4" v-for="comment in comments">
//...loop works fine
//Reply section
</li<ul class="children">
<li id="li-comment-6" v-for="reply in comment.replies">
//comment.replies does not work
</li>
</ul>
</li>
</ol>
As you can see in the code below comment.replies does not return the object I am waiting for.
How can you get the same result with vue?

multiple variables in routes. A route isn't leading to the controller defined blade

I have "show" and "edit" two routes. It's showing two different url. But "edit" route is using the 'show' blade, which is the SAME as the "show" route. How to lead the "edit" route to the 'edit' blade?
here is the web.php:
Route::get('/{user}/{course}', 'CoursesController#show')->name('course.show');
Route::get('/{user}/edit_{course}', 'CoursesController#edit')->name('course.edit');
here is the controller:
public function edit(Course $course) {
return view('courses.edit', compact('course'));
}
public function show(Course $course) {
return view('courses.show', compact('course'));
}
here is the index blade:
<a class="btn btn-xs btn-primary" href="{{ route("course.show", [auth()->user()->username, $course->title. $course->id] ) }}"> VIEW </a>
<a class="btn btn-xs btn-info" href="{{ route("course.edit", [auth()->user()->username, $course->title. $course->id]) }}"> EDIT </a>
Change the order or your routes in your routes files web.php
Route::get('/{user}/edit_{course}', 'CoursesController#edit')->name('course.edit'); //This one goes first.
Route::get('/{user}/{course}', 'CoursesController#show')->name('course.show');
Your show route is working as a wildcard if you invert the order as shown the edit route will catch it first when the second variable begins with edit_.

Homepage won't show newly added records but other pages do

I'm using a Laravel 5.7 in an old web project last year 2019 but now I encountered a very weird bug.
This is a website that when you add a new game, it will show to the menu list and if it is featured it will show to the homepage content.
this is the table ['game_id', 'name', 'key', 'status', 'order', 'is_featured']
in the header view I put this code:
<ul class="nav-menu">
<li class="{{ ($page == "games" ? 'menu-active' : '') }} submenu dropdown"><a href="/games" >Games</a>
<ul class="dropdown-menu">
#foreach(GetPublishedGames() as $game)
<li class="nav-item">{{$game->name}}</li>
#endforeach
</ul>
</li>
...
calling this helper code GetPublishedGames()
function GetPublishedGames(){
$data = DB::table("game")->where("status", 1)->orderBy("order")->get();
return $data;
}
in the homepage controller I had this line
"feat_games" => Game::where("status", 1)->where("is_featured", 1)->orderBy("order")->limit(5)->get(),
that calls in the homepage view:
#if(count($feat_games))
#foreach($feat_games as $feat_game)
<div class="feat-game-item wow fadeInUp">
... some content ...
</div>
#endforeach
#endif
I have no idea why this happening, it works before in the local and development stage. I did tried to clear cache.
any idea?

I am new in laravel and I want to announcement on homepage

Actually I want to display admin announcement or any notification on home page so when ever any user will be login with credentials detail so he or she can see announcement or notification..
please help me step by step , if possible with code logic, please do for me thank you very much
as you requested for full step by step process try this
first make form in your admin panel like this
<form method="post" action="{{ route('announcement') }}">
<label>Enter Your Announcement</label>
<textarea class="form-control" name="text">
</textarea>
<select name="active_status">
<option value="0">Deactive</option>
<option value="1">Active</option>
</select>
</form>
open your route/web.php make post method
Route::post('/announcement', [
'uses' => 'AdminController#postAnnouncement',
'as' => announcement
]);
if you have AdminController and its okay if not make it with these commands
php artisan make:controller AdminController
now you can add your function for save your announcement to database
public function postAnnouncement(Request $request){
$announcement = new Announcement;
$announcement->text = $request->text;
$announcement->active = $request->active_status;
$announcement->save();
return back()->with('status', 'Announcement Posted Success');
}
add use App\Announcement; in top of your controller
now you need to make announcement table and model
php artisan make:model Announcement -m
it will generate 2 file model & migration
go to database/migration folder and add this line to announcement migration after
$table->increments('id');
$table->string('text');
$table->boolean('active');
your table is ready to migrate now
php artisan migrate
now you can show in your homepage like this
first goto your homecontroller & add these lines
$announcements = App\Announcement::where('active', true)->get();
return view('home', compact('announcements'));
in your home.blade.php file
//Only for Authenticated Users
#auth
#foreach($announcements as $announcement)
<p>{{ $announcement->text }}</p>
#endforeach
#endauth
//Only for Guest Users
#guest
#foreach($announcements as $announcement)
<p>{{ $announcement->text }}</p>
#endforeach
#endguest
You can do it simply with the help of built-in user model.
First, check if the user is authorized and after that, you can show the announcement section.
All this should be done in the view of your page. you can do something like this
#if (Auth::check())
//show authorized content (Announcements etc.)
#else
//show unauthorized content
#endif
Or you can also do this in laravel 5.6
#auth
// The user is authenticated...
#endauth
#guest
// The user is not authenticated...
#endguest
Also do some research for this there are plenty of examples there on the Internet.
Try This
#auth
// For Logged in users only
<h1> You Are Loged In</h1>
#endauth
#guest
// For Guest Users
<h1> You Are Guest </h1>
#endguest
#auth
//if user logged in
<h1> You Are Loged In</h1>
#else
else guest
<h1> You Are Guest </h1>
#endauth

Resources