Laravel calling controller function from blade file not working - laravel

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...

Related

Method Illuminate\Auth\SessionGuard::users does not exist in 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

(Laravel 8.x) Get Data From DB and Use It Directly From Master Layout without Passing It From Parameters

My Problem
Framework : Laravel 8.x
I want to call my menu from DB and use it at layout.blade.php, but I'm using this layout.blade.php as my Master Layout of my view, so it's just and extends from other view.
So, I called is this way.
layout.blade.php
<!DOCTYPE html>
... some codes ...
<!-- Menu Navigation Before Using DB -->
<ul>
<li>Menu 1</li>
<li>Menu 2</li>
<li>Menu 3</li>
<li>Menu 4</li>
<li>Menu 5</li>
</ul>
<!-- Menu Navigation After Using DB -->
<ul>
#foreach ($menus as $menu)
<li>{{ $menu->name }}</li>
#endforeach
</ul>
<!-- Body Content -->
#yield('body_content')
IndexController.php
public function index()
{
return view('index_page', ['menus' => $getMenusFromDB]); //just for example
}
index.blade.php
#extends('layout', ['menus' => $menus])
#section('body_content')
<p>Hello World !</p>
#endsection
I have so many views linked to this layout, so I can't pass a menus parameter like this.
My Question
How can I use this $menus called from DB directly to use it at layout.blade.php without passing it from my extended view ?
:) You're in luck! Laravel has a pre-built feature to share data with all views. Do check out their Docs!
For example:
App\Providers\AppServiceProvider.php
use Illuminate\Support\Facades\View;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
// Just do it like how you would normally pass data with view helpers
View::share('$menus', '$menuFromDB');
}
}
layout.blade.php
<ul>
#foreach ($menus as $menu)
<li>{{ $menu->name }}</li>
#endforeach
</ul>
App\Providers\AppServiceProvider.php
Pass data in all views then use simple Asterisk * character
use App\Model\Menu;
class AppServiceProvider extends ServiceProvider
{
public function boot() {
view()->composer('*', function ($view) {
$menu = Menu::get()->toArray();
$view->with('menu', $menu);
});
}
}
Pass data in specific View then use this one,
view()->composer('profile', function ($view) {
$view->with('menu', $menu);
});
pass all common data here and used it in the blade directly.
More Info - https://laravel.com/docs/8.x/views#sharing-data-with-all-views

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?

I have problem with my code "UNDEFINED INDEX"

There is link to my previous problem where is code,maybe it helps you
Parse error: syntax error, unexpected '__construct' (T_STRING), expecting function (T_FUNCTION) or const (T_CONST)
this is problem i get
Undefined index: item (View: C:\xampp\htdocs\laravel\resources\views\shoppingCart.blade.php)
this error is there <strong><?php echo e($product['item']['name']); ?></strong>
this is my route
Route::get('shoppingCart', 'WebController#shoppingCart')->name('get.shoppingCart');
this is in my webcontroller
public function shoppingCart(){
if(!Session::has('cart')){
return view('shoppingCart');
}
$oldCart = Session::get('cart');
$cart = new Cart($oldCart);
return view('shoppingCart',['products'=>$cart->items]);
}
this is link for cart
<li>CART <span class="badge">{{Session::has('cart') ? '!' : ''}}</span></li>
And this is my code for shoppingCart
#extends('layouts.main')
#section('content')
#if(Session::has('cart'))
<div>
<div>
<ul class="list-group">
#foreach($products as $product)
<li class="list-group-item"></li>
<strong>{{$product['item']['name']}}</strong>
<li>Odstrániť</li>
#endforeach
</ul>
</div>
</div>
#else
<div>
<h2>V košíku nemáš žiadne položky!!!</h2>
</div>
#endif
#endsection
Firstly you can check if you have data or not on $cart->items while writing dd($cart->items); on the your function . Follow my comments .
public function shoppingCart(){
if(!Session::has('cart')){
return view('shoppingCart');
}
$oldCart = Session::get('cart');
$cart = new Cart($oldCart);
//dd($cart->items) /*uncomment this and check if you have data or not if you have no then problem is */
return view('shoppingCart',['products'=>$cart->items]); /* on the other if you have data dont forget those line and look at my comment on blade.php */
}
Your blade.php
#extends('layouts.main')
#section('content')
#if(Session::has('cart'))
<div>
<div>
<ul class="list-group">
#foreach($products as $product)
<li class="list-group-item"></li>
<strong>{{$product['item']['name']}}</strong>
<!--Look at here you remembe you were add products writing `['products'=>$cart->items]` then you be care calling your datas first you be relay on your codes you are working array (it seems you are working with objects then you need to call it $products->item->name Secondly you remember on the function you were add your data `['products'=>$cart->items]` like this if there is no child items object on $cart->items then you need to call it like
foreach($products as $product))
{
echo $product->name; //if it is array then echo $product['name'];
}
-->
<li>Odstrániť</li>
#endforeach
</ul>
</div>
</div>
#else
<div>
<h2>V košíku nemáš žiadne položky!!!</h2>
</div>
#endif
#endsection

Laravel:Passing variable from controller to view

chatcontroller.php function returns variable to view:
public function getChat()
{
$message = chat_messages::all();
return View::make('home',compact($message));
}
this is my route:
Route::get('/getChat', array('as' => 'getChat','uses' => 'ChatController#getChat'));
this is my home.blade.php:
#extends('layouts.main')
#section('content')
<div class="container">
<h2>Welcome to Home Page!</h2>
<p> <a href="{{ URL::to('/logout') }}" > Logout </a></p>
<h1>Hello <span id="username">{{ Auth::user()->username }} </span>!</h1>
<div id="chat_window">
</div>
<input type="text" name="chat" class="typer" id="text" autofocus="true" onblur="notTyping()">
</div>
<ul>
#foreach($message as $msg)
<li>
{{ $msg['sender_username']," says: ",$msg['message'],"<br/>" }}
</li>
#endforeach
</ul>
<script src="{{ asset('js/jquery-2.1.3.min.js') }}"></script>
<script src="{{ asset('js/chat.js') }}"></script>
#stop
I am trying to send result returned by select query to view from controller.
when I do this from homecontroller.php then it works fine.
if I try to pass from controller which I have defined it gives error message as:Undefined variable.
I have used the extends \BaseController do i need to do anything else to access my controller variable from view.
please suggest some tutorial if possible for same.
Verify the route to be sure it uses the new controller:
Route::get('user/profile', array('uses' => 'MyDefinedController#showProfile'));
First of all check your routes, as Matei Mihai says.
There are two different ways to pass data into your view;
$items = Item::all();
// Option 1
return View::make('item.index', compact('items'));
// Option 2
return View::make('item.index')->with('items', $items); // same code as below
// Option 3
View::share('item.index', compact('items'));
return View::make('item.index);
You can also do this:
$this->data['items'] = Item::all();
return View::make('item.index', $this->data);

Resources