laravel-4,eloquent,undefined , posts and attachments, Undefined property: Illuminate\Database\Eloquent\Collection::$name

posts and attachments, Undefined property: Illuminate\Database\Eloquent\Collection::$name


Tag: laravel-4,eloquent,undefined

when i try to get the attachment's name like this:


i get the following error

Undefined property: Illuminate\Database\Eloquent\Collection::$name (View: C:\wamp\www\Sites\app\views\public\categories\show.blade.php)

Post model

class Post extends \Eloquent implements SluggableInterface {

    public function category(){
        return $this->belongsTo('Category');

    public function attachments(){
        return $this->hasMany('Attachment');


Attachment Model

class Attachment extends \Eloquent {

    protected $fillable = ['name', 'type', 'extension', 'user_id', 'post_id', 'size'];

    public function post(){
        return $this->belongsTo('Post');


class CategoriesController extends \BaseController {

    public function show($id, $slug = null)

        $category = Category::find($id);

        $posts = Post::whereCategoryId($category->id)->orderBy('date', 'DESC')->paginate(4);

        return View::make('', compact('category', 'posts'));


categorie View

@foreach($posts as $post)
   {{$post->title}} // work fine
   {{$post->body}} // work fine

   {{$post->attachments}} // return this :
            "created_at":"2015-01-29 13:04:35",
            "updated_at":"2015-01-29 13:04:35",

any ideas?!!!


According to your relationship definition there can be many attachments, that means the relation will return a collection of models. You can either get only the first one:

@if($attachment = $post->attachments()->first())
   {{ $attachment->name }}

Or loop over all attachments

@foreach($post->attachments as $attachment)
    {{ $attachment->name }}


Merging collections

I have a raw query: $data = Product::hydrateRaw(//sql here); This returns a collection. I then perform a further query: $data2 = Product::take(3)->get(); I then wish to merge both collections: $data->merge($data2); Unfortunately the merge appears to have no effect, when I dd() the collection only contains $data and not $data2. Where...

Why do I need use 'with' in Laravel Eloquent?

First of all, sorry for my bad English. I have Eloquent query $gigs = Gig::active() ->plusGigs() ->with('member') ->paginate(16); and I have with function in my model public function member() { return $this->belongsTo('App\User', 'USERID', 'USERID') ->select(array( 'USERID', 'username' )) } when I try to use on my view file {{ $gig->member->username...

How can I move file in php Laravel 5 ?

I'm trying to move file from one place to another place. In this case is my user profile picture. Since I store my user profile picture base on their username, so when they change their username. I will need to move thier profile photo, Otherwise, the image link will be...

Laravel: Retrieve polymorphic attributes efficiently

My actual Question is: How to return attributes to the client which I actually need, throw the rest away and be as efficient as possible? So, I have a construction where I basically have media objects, which can be of different types, like video, picture, link and so on. This...

Laravel 4.2 Sending email error

Hello everyone I have an error in laravel when I am sending an email. I have a form with a select tag and when I select the user and click submit I need to send him a mail after I select it. Here is my Controller method: public function store()...

Retreiving a single colum from a pivot table - Laravel 5

I am using a pivot table genre_user to relate user to genre. table contains the following fields id user_id genre_id Following are the model definitions User.php public function genres() { return $this->belongsToMany('App\Genre'); } Genre.php public function artists() { return $this->belongsToMany('App\User'); } I am getting the results as a collection when...

Error in laravel 4

When i try to log in , it redirects me to{username} but it shows a NotFoundHttpException error. Thank you in advance! The routes.php file Route::get('/admin', '[email protected]'); Route::get('/logout', '[email protected]'); Route::get('profile', function() { return "welcome! Your username is" . Auth::admin()->username; }); Route::resource('sessions', 'SessionsController', ['only' => ['index', 'create', 'destroy', 'store']]); here is...

Matched data inside select supposed to selected by default

I have a database that contains project_development and developer. I want to make an edit form for the project_development that has select with option from developer table. when the data matches, the current option will be selected. It works fine on other select without the foreach loop statement. <select class="form-control"...

Caching issue in angularJS application

I've an admin panel which is a pure angularJS application, which uses REST api for data manipulation. REST api is built using SlimAPI framework and Laravel's Eloquent ORM. I'm facing caching issue in admin panel. Even though if a add new content to the system, it'll not show up in...

Issues on routes and blade with dynamic variable

i have this Route code Route::get('/{slug}', function($slug) { return View::make('page'); }); ...let say, my url $slug is "about" as the value, inside my page.blade.php will need to see this $slug "about" and output it as @include('$slug') where the $slug should be the about in short, i would like to happen...

Laravel get posts with multiple tags

I'm working with a laravel belongsToMany relationship between Post and Tag. What I'm trying to do is get all Posts where it has multiple tags. I've tried all sorts of eloquent queries, but I can't get it at all. Currently I can get an array of post_id's and tag_id's, as...

run laravel downloaded project on local machine

i am newbie trying to install an Laravel Framework project run on my local machine. Laravel Framework-4 already installed Package downloaded - now i get error when i try to compose please help me guys thanks in advance....

How properly select data from DB according to filter in Eloquent?

I have a filter. Filter contains three fields. Call_Date_From, Call_Date_Till, Telephone. So I need to select from LEADS (Lead Model) table all rows that fit filter. In raw Php + MySQL I would write something like this: $sql = ' WHERE '; $post['call_date_from'] ? $sql .= ' `call_date` >= '...

Automaticlly attach to pivot table in Laravel 5

I currently have a Users to Groups Relationship (ManyToMany) with a pivot table group_user. I want the user to be able to create a group but once creating the group, how do I make it, that the creator becomes member of this group? Currently I have My Pivot Table (group_user):...

Creating an Eloquent Object with relation included

I'm pretty much new to opps and laravel both So, to insert the values into my users and profiles table which hav OneToOne relationship, Here is how my store() method looks like public function store(Requests\StoreNewUser $request) { // crate an objct of user model $user = new \App\User; // now...

how to add custom dynamic text footer in laravel 4.2 using dompdf

i have followed this example laravel-4-create-pdf-use-dompdf: how to add custom dynamic footer $dompdf = \App::make('dompdf'); $dompdf->loadHTML('<h1>naeem World!!</h1>'); anyone do have idea? or please suggest, i also have followed this solution DOMPDF add a header and footer but it doesn't work correctly. Edited: i want $db_data['footer_text'] to be footer text to...

how to save pdf in directory laravel 4.2 using dompdf

i have followed this example laravel-4-create-pdf-use-dompdf: i want to save pdf in directory not pdf preview in the browser. My current code: $pdf = \App::make('dompdf'); $pdf->loadHTML('<h1>Hello World!!</h1>'); return $pdf->stream("order_email.pdf"); but what this code is doing, it shows my "Hello World" text as PDF in the browser but not saving "order_email.pdf"...

Laravel get most out of the database

I'm having a tracker in Laravel 4 and I was wondering, how can I get the 'most' from my table. So want I want is to have the day that had the most visitors. My table structure looks like this: So, my controller looks like this: public function index() {...

How to skip a row with file exists condition in laravel

This is for a search query based on many input fields, i'm doing if statements inside the query based on the inputs, for example : $query = Model::all(); if($field = Input::get('field')) $query->where('column_name', $field); but what i want to do also is a condition to skip a row if there is...

2 Foreach Loop Inside A Table

I had Users table and group table, when i load a group table, it loads the user which have same group_id as the group table id. it works, but my problem is the foreach was quite a mess. the output looks like this.. however, i want to make the output...

How can i refactor my angular code for my laravel app so i have the controllers in separate files?

I would like to have the code as structured as possible and right now all my controllers and routes are kept in the same file. I am using laravel 4.2 for the back end and templating and angular for the front end part of the app. This is how the...

Eloquent Query always returns null for parent table using oneToOne relationship

Parent Table users schema | 'id','email','pass' Relationship public function profile() { return $this->hasOne('App\Profile','user_id'); } Other Table profiles schema | 'id','user_id'/*foreign key to users table */ ,'address','city' Relationship public function user() { return $this->belongsTo('App\User','id'); } I'm querying Profile model and would like it to eagerload with User model. public function edit($id){...

findOrFail laravel 5 function for specific filed

This is my code: $get_all = Geo_Postal_us::findOrFail($postal); With this query,laravel try to find ID filed in table. I don't have id filed, for primary key i have postal column. So, how to set function to find value in postal column, not to search from id column ? Thanks,...

Laravel Undefined index Error in array values display

I am using Laravel 4.2. I have two mysql tables OwnTable, OtherTable. I am getting values successfully from these tables through php. My further PHP code look like below to display values in blade php, if (!empty ($OwnTable)){ foreach($OwnTable as $owntbl){ $Finalvalue['OwnValue']['Name'] = $owntbl->Name; } } if (!empty ($OtherTable)){ foreach($OtherTable...

Error while Eager loading a Eloquent model with multiple relationship in Laravel 5

My User model have two relationships public function group(){ return $this->belongsTo('App\Group','group_id'); } public function profile() { return $this->hasOne('App\Profile','user_id'); } And Accessing them in Controller like $users = \App\User::with('group','profile')->get(); However, Retriving Profile Model's column give error (Inside a @foreach loop ) @foreach ($users as $user) URL::action('[email protected]',[$user->profile->id]) @foreach ($users as $user) Error...

Laravel 4 - Scope to only show rows where another DB has no relational items

I have a cars table, and a car_image table. I want to get all the cars that have NO images in the car_image. In my car model I am making a scope: public function scopeNoImages($query) { return $query-> ?? } How can I create a scope that will show only...

Laravel 5 No query results for model redirect page

I have simple form that post values to a controller,everything works fine if a result is returned from the controller , but if there is no result I get error the following error: No query results for model Which works as it should. My question is : Is it possible...

Laravel relation many to many with additional pivot

Status Update I have implemented morph to many relationship type but how can I insert into the addition field? The code for the polymorphic relation is: public function mailmessages() { return $this->morphToMany('Mailmessage','rel','mailmessage_rels','rel_id','mailmessage_rel_id') ->withPivot(['addition']); } Original Post I have a Laravel project that uses many to many relations and in the...

Laravel Eloquent how to return one to many to many collection

Is it possible to get an eloquent relation based on a One->Many->Many relationship? In the below example, I would want to get all of the gallery_votes for a given user. users +----+---------------+ | id | user_name | +----+---------------+ | 1 | bob | | 2 | sam | +----+---------------+ galleries...

foreach loop not working with laravel queue

I am using sync (local driver) for pushing up a queue in a update method of EmailCampaignController, which uses another method of the same controller named emailQueue like this Queue::push('[email protected]', array('campaign_id' => $campaign_id)); The emailQueue uses a foreach loop which runs correctly for once after that it gives error as...

Mailchimp returns true but email not in list of subscribers

Laravel 4.2 Mailchimp Library: I have already created a list and added two subscribers in Mailchimp GUI. <?php $list_id = '******'; $email_address = '[email protected]'; $subscriber = MailchimpWrapper::lists()->subscribe( $list_id, array('email'=>$email_address) ); return Response::json ( [ 'response' => $subscriber ] ); ?> Response is true { "response": { "email": "[email protected]", "euid":...

Laravel Blade: Increment variable by 1 each time?

Using Laravel blade template, is there a way to include a variable and increase each time in the foreach or what is better approach? For example: @foreach($categories as $category) <li><a href="#tab_c1" role="tab" data-toggle="tab">{{$category->name}}</a></li> @endforeach In the foreach block, the value from #tab_c1 will need to be increase. eg: #tab_c1, #tab_c2,...

Sync element to a child on Laravel

My Shema database is User Table id login parent Sign Table id name user_id (Sign owner) Pivot table user_sign id user_id sign_id My User model contain public function signs() { return $this->belongsToMany('App\Sign', 'user_sign'); } public function parent(){ return $this->belongsTo('User', 'parent'); } public function children(){ return $this->hasMany('User', 'parent', 'user_id'); } And...

count() “where” statement in Laravel blade?

I am interested in displaying quick counts of email stats in my application, but I'm getting hung up on finding an efficient way to generate the counts. I am hoping to just use the eloquent relationship with some sort of "count where" statement inside of blade. Getting the total count...

Laravel 5 form request validation returning forbidden error

I am trying to use Laravel 5.1's form request validation, to authorize if the request is from the owner. The validation is used when the user is trying to update part of the table clinics through the show.blade.php. My set up so far: routes.php: Route::post('clinic/{id}', array('as' => 'postUpdateAddress', 'uses' =>...

Querying one-to-one in laravel

I have two models city and business.I have to perform below queries Find Business by city name. Find Top 10 cities which have the maximum business. Here is the models Business class Business extends \Eloquent { protected $fillable = [ 'business_type', 'first_name', 'last_name', 'email', 'password', 'designation_id', 'name', 'description', 'portfolio_id', 'image',...

JavaScript click function table cell only applied on the first row

I had a JavaScript click function on a table row, but when I click it, the function only works on the first row. How do I fix this? <script type="text/javascript"> $(document).ready(function(){ $('#detpanel').hide(); $("#showdet").click(function(){ $('#detpanel').slideDown(500); }); $("#hidedet").click(function(){ $('#detpanel').slideUp(500); }); $('#showdet').hover(function(){ $(this).divhover("background-color", "yellow"); }); }); </script> <tbody> <?php $i = 0; ?>...

Eloquent model not updating updated_at timestamp

I'm using Laravel 5.1. To make it simple, I have the following code Migration: Schema::create('sitemap_data', function (Blueprint $table) { // Primary and foreign keys $table->increments('id'); $table->string('postUrl'); // Database functions $table->timestamps(); }); And this is the code somewhere else I'm using $sitemapData = SitemapData::firstOrNew([ 'postUrl' => $post ]); $sitemapData->save(); Now, according...

How to perform a statement inside a query to check existence of a file that has the query id as name with less resources in laravel

i'm looking for away to see if the query 'id' has a folder with the same id as name in the file system, i did it but it will slow down the drive in the future with lots of files $query = Model::all(); if(Input::get('field') == 'true'){ $filenames = scandir('img/folders'); $query->whereIn('id',...

How to sum groupBy in Laravel5

Is a simple question about Eloquent , this eloquents returns correctly the user group by name $pujas = Bid::orderBy('created_at','desc')->take(10)->usuarios()->subasta()->groupBy('id_user')->get(); I need to sum the value of the users import in the auction, the row is called 'importe', the result now with this eloquent is this : UPDATE QUESTION I managed...

Laravel: dynamic where clause with Elouquent

I am calling URL with search params which are dynamic. How could I form proper Eloquent query? In theory: query query where(someParam1) query where(someParam2) query orderby(someParam3) query get I need this kind of structure so I can use where clause if param exists. If there is some other way in...

Laravel - Guzzle not returning any data even though URL is correct

I am trying to return the JSON data from a third party API - I currently have in my controller: $client = new Client(); $request = $client ->get(''.Input::get('postcode')); $statusCode = $request->getStatusCode(); if ($statusCode >= 200 && $statusCode < 300) { $json = Response::json($request); // Returns JSON decoded array of...

Nested comments with Laravel

I'm currently trying to replicate something similar to a forum, but I'm stumped on how I could create nested comments. I understand that for regular replies I could create a replies table and run a loop for each comment that matches the thread id. But I don't know how I...

Laravel belongsTo throwing undefined function App/BelongsTo() exception

I have a comments table and user table with the relationship: user->hasMany('comments') and comment->belongsTo('user'). For some reason with which eludes me, I keep getting this FatalErrorException in Comment.php line 22: Call to undefined function App\belongsTo() My other models have no issue whatsoever with the HasMany relations, however, the comments model...

Laravel 5.0: Form::select() called twice Eloquent Accessor by select name

Blade template: {!! Form::model($category) !!} {!! Form::select('drinks_id', [...full list...]) !!} {!! Form::close() !!} 'drinks_id' called by Eloquent Accessor: public function getDrinksIdAttribute() { var_dump('get'); return 123; } When Form::select('drinks_id') execute, getDrinksIdAttribute() called twice and print string(3) "get" string(3) "get" from var_dump(). If I write this: {!! Form::model($category) !!} {!! var_dump($category->drinks_id) !!}...

Retrieving the Slug from URL for function (Laravel 5)

I'm making an App where a group is created by a user. This user can go to the group page (automated unique slug is created for the groups). My goal is for the member who created the group, to be able to make a invite code for that specific group....

Proper use of Array and Foreach at Laravel

I don't understand how to convert my PHP array into Laravel, I am new to Laravel and can't even find exact format to follow it. I would like to use it on my blade file. Here's my php code. $properties = array('office', 'retail'); foreach ($properties as $property) : echo $property;...