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

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);
}

Related

how to access function defined in model to view?

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())

Laravel: Access collection in view

I would like to display users that have sent or got message/s.
User Model:
public function messages_sender()
{
return $this->hasMany('App\Message', 'sender_id');
}
public function messages_recipient()
{
return $this->hasMany('App\Message', 'recipient_id');
}
MessageController
public function index()
{
$users = User::with('messages_recipient', 'messages_sender')->paginate(5);
//return $users;
return view('message.index',compact('users'));
}
Messages View:
{{ $user->messages_recipient['recipient_id'] }}
Result is an error in view "Undefined index: recipient_id" or when i try to access any of them (sender_id, recipient_id). I understand that not all users have messages, as i see in JSON format, so i used:
#if($user->messages_recipient->has('recipient_id'))
{{ $user->messages_recipient['recipient_id'] }}
#endif
and than error did not show.
JSON: https://pastebin.com/NFSWMp7r
As I am new to Laravel i could use some help. In similar example it worked when I needed to get users and name of their role (admin, user).
You can access the Users form the App\Message Model instead of the other way round.
Message Model:
public function senders()
{
return $this->belongsTo('App\Users', 'sender_id');
}
Message Controller
public function index()
{
$senders = Message::senders()->paginate(5);
return view('message.index',compact('senders'));
}
Dont blame me but I am not sure, if the sender_id is just right there :-P
Unfortunately, if you want unique records this will not work.
Your using the message_recipient as an array and if a key doesn't exist on an array PHP will always throw an error. The hasMany relationship returns a Collection of Message objects so you would need to use it as an object with:
#foreach($user->messages_sender as $message)
{{ $message->id }}
#endforeach
and
#foreach($user->messages_recipient as $message)
{{ $message->id }}
#endforeach
or if you just wanted all of the message ids you could do $user->messsages_recipient->pluck('id') and that would return all of the ids of the Message objects.

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

how to acces nested objects in blade templates

Let me show you what I have.
//Post Controller
public function showPost(Post $post)
{
$albums = $post->album()->with('photos')->get();
$comments = $post->comments()->where('approved', '=', 1)->get();
$this->layout->title = $post->title;
$this->layout->main = View::make('home')->nest('content','posts.single', compact('post', 'comments','albums'));
}
mysql sentence executed correctly
string 'select * from albums where albums.id = '{"id":19,"title":"Post no 19","read_more":"Lorem i'... (length=786)
string 'select * from albums where albums.post_id = '19'' (length=54)
string 'select * from images where images.album_id in ('4')' (length=57)
I want to access the Photo object in blade, everything parses to the template but when I try to get the Photos
#foreach($albums->Photos as $photo)
Undefined property: Illuminate\Database\Eloquent\Collection::$Photos (View:
// post model
public function album()
{
return $this->hasOne('Album');
}
//album model
public function Photos(){
return $this->hasMany('Image');
}
Try
#foreach($albums->Photos()->get() as $photo)
{{$photo->attribute}}
#endforeach
You need to call the function that holds the relationship then use
get()
method to return an Eloquent Collection and then iterate it with a foreach loop.
#foreach($albums as $album)
#foreach($album->Photos as $photo)
<p>{{ $photo->image }}</p>
#endforeach
#endforeach
THats the answer

Resources