how to access function defined in model to view? - laravel

my laravel model funciton :
public function isAdminOrSuperAdmin()
{
return $this->role() == config('custom_config.constants.user_types.SUPER_ADMIN')
|| $this->role() == config('custom_config.constants.user_types.ADMIN');
}
i try to access in view :
#if($user->isAdminOrSuperAdmin())
<a class="btn btn-primary pull-right" style="margin-top:
-10px;margin-bottom: 5px" href="{!! route('admin.users.create') !!}">
Add New
</a>
#endif
but it show error:
Method Illuminate\Database\Eloquent\Collection::isAdminOrSuperAdmin does not exist. (View:/resources/views/admin/users/index.blade.php)
thanks in advance.

Check the error:
Method Illuminate\Database\Eloquent\Collection::isAdminOrSuperAdmin does not exist. (View:/resources/views/admin/users/index.blade.php)
This means, you are trying to call a method of your model on a Collection instance instead of an actual User model instance.
When querying several items from your database, Laravel returns an instance of the Collection class that contains all the resulting model objects.
Maybe you are doing something like this:
public function aCoolFunction()
{
$user = User::where('column', 'value')
->get(); // <-----
return view('my_view')->with('user', $user);
}
The get() method returns a Collection, not a single element.
Try the first() instead:
public function aCoolFunction()
{
$user = User::where('column', 'value')
->first(); // <-----
return view('my_view')->with('user', $user);
}
Now in your view the $user variable will actually hold and instance of your User model user in which the isAdminOrSuperAdmin() method is defined, and not a collection of it.

I don't think this is the best way but you can pass the function to view using your controller :
in your controller :
public function index(User $user)
{
$ModelFunction = $user->yourModelFunction();
return View('test',compact('user','ModelFunction'));
}
And in your View :
{{ $ModelFunction }}

you must call function like this:
#if(is_admin_or_super_admin())

Related

How to return an int variable from controller to view in Laravel?

I have created a global variable in my CartController for the quantity of an item, here is the declaration:
class CartController extends Controller
{
// defining global quantity variable
private $quantity = 1;
Then in my index() function on the same controller, where I return the view, I pass through the quantity variable like so:
public function index()
{
$this->quantity;
return view('cart.cart', ['quantity' => $this]);
}
But when I call it in the cart.blade.php file like this:
<div class="display-quantity">
{{-- Shows Quantity --}}
<span class="item-quantity" id="item-quantity">{{ $quantity }}</span>
</div>
It gives me the following error:
TypeError
htmlspecialchars(): Argument #1 ($string) must be of type string, App\Http\Controllers\CartController given (View: /Users/rosscurrie/mobile-mastery-latest/resources/views/cart/cart.blade.php)
I think I need to convert it to a string but I need to work with it as an integer so how do I get around this? Thanks!
It look like you're passing in $this as the quantity.
Try changing your controller's index() code to something like:
public function index()
{
$myQuantity = $this->quantity;
return view('cart.cart', ['quantity' => $myQuantity]);
}
It looks like the confusion here is with the -> operator which in php is used to call on object's method or access an object's property the same way . works in Javascript. This statement $this->quantity; accesses the quantity property of $this, so to use it - you need to assign it to a variable (or use it directly). This would have also worked:
public function index()
{
return view('cart.cart', ['quantity' => $this->quantity]);
}
You can always do things like dd($this->quantity); to ensure you are working with the correct information.

Method Illuminate\Database\Eloquent\Collection::links does not exist

I created a model relationship between User and Message. I want to implement a list of messages for the authenticated user but I get the following error.
Method Illuminate\Database\Eloquent\Collection::links does not exist
Controller
public function index()
{
$user_id = auth()->user()->id;
$user = User::find($user_id);
return view('message.index')->with('messages', $user->message);
}
Message provider
class message extends Model
{
public function user() {
return $this->belongsTo('App\User');
}
}
User provider
public function message ()
{
return $this->hasMany('App\Message');
}
index.blade.php
#extends('layouts.app')
#section('content')
<h1>messages</h1>
#if(count($messages)>0)
#foreach ($messages as $message)
<div class="well">
<h3>{{$message->user}}</h3>
<small>Written on {{$message->created_at}} </small>
</div>
#endforeach
{{$messages->links()}}
#else
<p> no post found </p>
#endif
#endsection
Error
"Method Illuminate\Database\Eloquent\Collection::links does not exist.(View: C:\xampp\htdocs\basicwebsite\resources\views\message\index.blade.php)"
Check your view blade, that method (links()) only could be used when your data model is implementing paginate() method.
If you dont use paginate(), remove this part:
{{$messages->links() }}
If you are trying to paginate your data when it gets to the view then you need to add the paginate in your controller before passing the data to the view. Example
return $users = Users::select('id','name')->paginate(10);
with that paginate method in your controller, you can call the links method to paginate your object in view as shown below
{{$users->links()}}
hope it helps you
There are 2 ways to resolve this issue:
Either use paginate function while searching data from database:
$users = DB::table('users')->where('id',$user_id)->paginate(1);
Remove links() function from index.blade.php
{{ $messages->links() }}
Remove {{ $messages->links() }} to in your index.blade.php because {{ $messages->links() }} is supported only when you use paginate
You can do something like this in your controller file.
public function index()
{
$messages = Message::all()->paginate(5);
$user_id = auth()->user()->id;
$user = User::find($user_id);
return view('message.index')->with('messages', $messages, $user->message);
}

Trying to get property 'post_titile' of non-object

This is My Controller.
public function show(Posts $posts)
{
$page = Posts::find($posts->id);
//dd($page);
return view('web_views.index',['page' => $page]);
}
This is my view page
<h4>{{$page->post_titile}}</h4>
It's better to use Route-Model Binding I think.
Your route (if you are using resource route, it's already done):
Route::get('posts/{post}', 'PostController#show); // domain.tld/posts/1
Your method should look like this:
public function show(Post $post)
{
return view('web_views.index',compact('post'));
}
In your view:
<h4>{{ $post->post_titile }}</h4>
May be $posts->id you are passing, has no result in database so you need to check it by using if-statement
public function show(Posts $posts)
{
$page = Posts::find($posts->id);
if($page == null){
$page = ['post_title' => 'Not Available'];
}
return view('web_views.index',['page' => $page]);
}
I believe this error is because of not finding data for an ID into database. So if as per above script will pass the fetched data to view otherwise it will push an item into $page array.

How to call multiple methods or controllers to a same route in laravel

Find below the controller code with two methods and suggest me how to call these two methods in the same route or whether I have to create two different controllers for the same page(route).
class TicketController extends Controller
{
public function show(){
$results=Whmcs::GetTickets([
]);
return view('clientlayout.main.index',compact('results'));
}
public function set(){
$test=Whmcs::GetInvoices([
]);
return view('clientlayout.main.index',compact('test'));
}
}
The route file:
Route::get('clientlayout.main.index','TicketController#show');
Route::get('clientlayout.main.index','TicketController#set');
Find the code in the blade file and after running this I'm getting an error
undefined index:Results.
#foreach($results['tickets']['ticket'] as $key)
{{$key['subject']}}
#endforeach
#foreach($test['invoices']['invoice'] as $value)
{{$value['firstname']}}
#endforeach
When I run these two foreach loops in a different blade file it executes correctly, but I need these two results to be viewed in the same file.
How to view both tickets and invoices in the same index page?
Combine the two controllers into one and perform both queries in a single method:
class InvoiceTicketController extends Controller
{
public function show(){
$tickets = Whmcs::GetTickets([]);
$invoices = Whmcs::GetInvoices([]);
return view('clientlayout.main.index',compact('tickets', 'invoices'));
}
}
Then update one of the those routes to use the combined controller:
Route::get('clientlayout.main.index','InvoiceTicketController#show');
You'll have access to both $tickets and $invoices collections in the blade file this way:
#foreach($tickets as $ticket)
{{ $ticket->subject }}
#endforeach
#foreach($invoices as $invoice)
{{ $invoice->firstname }}
#endforeach

Laravel: Retrieve data from DB and diplay in View

I have a bug here in my code that show me a probleme while displaying data in the home page
Controller
class Annonce_indexController extends Controller
{
public function index()
{
$annonce_residentiel = Annonce_residentiel::all();
return view('/' , compact('annonce_residentiel'));
}
}
Route
Route::get('/index','Annonce_indexController#index');
Blade View
{{ $annonce_residentiel->prix }}
It says that $annonce_residentiel is undefined
Edit:
The problem is I have two routes to the same view:
Route::get('/','Admin\Annonce_indexController#index');
Route::get('/',array('as' =>'viewville','uses'=>'VilleController#index'));
Solution
Change the second route to post !
Route::get('/','Admin\Annonce_indexController#index');
Route::post('/',array('as' =>'viewville','uses'=>'VilleController#index'));
$annonce_residentiel is an object and not a variable so you cannot just call it and expect it to pop a value. For just demo purpose and to understand how it works try the following code in your view.
#foreach($annonce_residentiel as $data)
{{ $data->prix }}
#endforeach
Controller
class Annonce_indexController extends Controller
{
public function index()
{
$annonce_residentiel = Annonce_residentiel::first();
return view('/' , compact('annonce_residentiel'));
}
}
Blade View
{{ $annonce_residentiel->prix }}

Resources