In my Laravel blade template, I have a table in which I want to add another column
after this code
<td>{{format_price($mission->amount)}}</td>
I added this :
#php
$amount_to_be_collected = DB::table('shipments')
->select('amount_to_be_collected')
->where('mission_id', $mission->id)
->get();
#endphp
<td>{{format_price($amount_to_be_collected)}}</td>
What is wrong with this code?
First of all, You should not put DB query code in your blade.
Now, when you run a query using eloquent and call get(), the response is a Collection::class instance that can be treated as an array but cannot be automatically transformed into a number/string.
If you only need the value of on field for one entry, use value() instead.
$amount_to_be_collected = DB::table('shipments')
->where('mission_id', $mission->id)
->value('amount_to_be_collected');
Note: It is not good to use db queries in blade views, you can also use helper
Try this before using DB facade you need to call this class in blade view Running Database Queries
use Illuminate\Support\Facades\DB;
Related
I'm trying to achieve pagination and it is working absolutely fine until I add sortByDesc() along with my eloquent query.
web.php (route file)
Route::get('/', function(){
$posts = Post::simplePaginate(5)->sortByDesc("post_id");
//sortByDesc("post_id") this causes the problem
}
When I prepare the view for the pagination with {{ $posts->links() }} in the specified view, I get the following error-
Method links does not exist
If I remove the sorting condition from the query, it works perfectly.
What can be the reason behind this behaviour?
Try putting the sort on the query rather than the pagination:
Post::orderBy('post_id', 'desc')->simplePaginate(5);
To extend to what #RossWilson said.
sortBy is a collection function, not an eloquent function, the correct eloquent function is orderBy.
Also, see simplePaginate() as if you were performing a get(), first(), find().
What would you place first the get or the order? ... maybe the get if you want to order a collection (with sortBy), but since simplePaginate does not return the same collection that a get() would return, sortby does not work. And probably messes up the pagination object/collection.
I am working on a project which requires me to get all the list of all information from a table --Just like in a blog, i used the all() method to do this but when i try to get the method i declared in my Model i get an error, saying
the collection instance does not exists
But when i use The
Model::find($id)->relationship()->name;
it works fine. Is there any way to load all relationship with the all() function in laravel.
Thanks for your help..
When you perform Model::find($id)->relationship(); you are actually accesing to the Dynamic relationships Properties
You need to convert it into a collection using Model::find($id)->relationship()->get();
Then you can perform any collection method to get the result you want. After doing this you can access to its attributes like this:
$model_varible = Model::find($id)->relationship()->get();
$model_variable = $model_variable->find($id)->name;
Let me know if this works for you.
You should use relationship without brackets to access the model:
Model::find($id)->relationship->name;
And use "with()" to populate the relationships:
Model::where('published', 1)->with('relationship')
I need to understand when/not to use get(); in Laravel 5.
PHP warning: Missing argument 1 for Illuminate\Support\Collection::get()
Google shows me answers to their issue but no one really explains when you should/not use it.
Example:
App\User::first()->timesheets->where('is_completed', true)->get(); // error
App\Timesheet::where('is_completed', true)->get(); // no error
Fix:
App\User::first()->timesheets()->where('is_completed', true)->get(); // no error
Noticed the timesheets() and not timesheets? Could I have a detail explanation for what is going on, please?
I'm coming from a Ruby background and my code is failing as I do not know when to use () or not.
I'll try to describe this as best I can, this () notation after a property returns an instance of a builder, let's take an example on relationships,
Say you have a User model that has a one-to-many relationship with Posts,
If you did it like this:
$user = App\User::first();
$user->posts();
This here will return a relationship instance because you appended the (), now when should you append the ()? you should do it whenever you want to chain other methods on it, for example:
$user->posts()->where('some query here')->first();
Now I will have a the one item I wanted.
And if I needed say all posts I can do this:
$user->posts;
or this
$user->posts()->latest()->get();
$user->posts()->all()->get();
So the key thing here is, whenever you want to chain methods onto an eloquent query use the (), if you just want to retrieve records or access properties directly on those records then do it like this:
$user->posts->title;
Well, ->timesheet returns a collection, where ->timesheet() returns a builder.
On a Collection you can use ->where(), and ->get('fieldname'), but no ->get().
The ->get() method can be used on a builder though, but this will return a collection based on the builder.
Hope this helps.
The 'problem' you are facing is due to the feature of being able to query relations
When accessing a relation like a property, ->timesheets, the query defined in the relationship is executed and the result (in the form of a Collection) is returned to you.
When accessing it like a method, ->timesheets(), the query builder is returned instead of the resulting collection, allowing you to modify the query if you desire. Since it is then a Builder object, you need to call get() to get the actual result, which is not needed in the first case.
When you use ->timesheets you are accessing a variable, which returns the value of it (in this case an instance of Collection).
When you use ->timesheets() you are invoking whatever is assigned to the variable, which in this case returns an instance of Builder.
whilst pascalvgemert's answer does answer your problem regarding Laravel, it does not explain the difference between accessing or invoking a variable.
In simple term
$user = App\User::get();
is used to fetch multiple data from database
rather
$user = App\User::first();
is used to fetch single record from database
I have several fields in a form with dates and times ('dd-mm-yyyy', 'hh:mm').
When I want to save the form I use my own function to convert it for MySQL ('yyyy-mm-dd', 'H:i:s') via date() which I added to save() in Laravel Model Class.
But where is single place where I can put the same function to format output (SELECT queries)?
There is no single function in Laravel for data output. find(), findOrNew(), findOrFail(), ... - there are in different classes so I cant use single place to add the formatting function.
Is there any proper place to put formatting function?
You can use Laravel Date Mutator. Just put the following method in your Eloquent Model:
Suppose your have a table user in your database with expireDate column. then define this field in your model.
class User extends Eloquent {
protected $dates = ['expireDate'];
}
Just Replace FirstName with your database column name.
Then you can use laravel Carbon class to format your result.
$user = User::find(1);
return $user->expireDate->format('d-m-Y');
For more reference please read the http://laravel.com/docs/4.2/eloquent#date-mutators
Just add this to AppServiceProvider#register:
Carbon::setToStringFormat('d/m/y');
Now you can just echo $model->created_at and everything’s formatted correctly.
In App directory, create a new directory. Let call it "libraries",
then create a php file "CustomFunction.php" or whatever, this has to be a class as well, then put your function in this class.
So you have
class CustomFunction{
static function dateFormat(){
}
}
in App/libraries/
Then in App/start/global.php
Iside classloader on line 14, as below, add the path to your new folder:
ClassLoader::addDirectories(array(
app_path().'/libraries'
));
Then in your composer.json file, add:
"app/libraries" to "autoload" array.
Then in your view you can easily do this:
{{ CustomFunction::dateFormat() }}
I'm on Laravel and Eloquent, and trying to populate a view's dropdown box with results of a select query.
In my controller:
public function uploadDocs($userid)
{
$doc_options = DB::select('select document.document_description from document where user_id = ?', array($userid));
return View::make('uploaddocs')->with('doc_options', $doc_options);
}
In my view:
<body>
{{ Form::select('doc_options_id', $doc_options) }}
</body>
I'm getting the following stack trace:
htmlentities() expects parameter 1 to be string, object given (View: /home/vagrant/code/eduview/app/views/uploaddocs.blade.php)
Any ideas? Thanks.
Try
$doc_options = DB::statement(DB::raw('select document.document_description from document where user_id = ?', array($userid)))->get();
Edit: I should probably explain first.
DB::select() is primarily used for the database builder in order to chain onto other chain-able functions, and not for doing your whole query.
You could use DB::statement to provide a new custom SQL query in it, but you also have to specify that the contents of the statement()'s parameter will be a raw query. Hence the DB::raw
Alternatively you could take advantage of Eloquent or Laravel's query builder by creating an Eloquent model called Document in app/models with contents as:
class Document extends Eloquent {}
and swap out your query above with:
$doc_options = Document::select('document_description')->where('user_id','=',$userid)->get()
You are passing an object into the Form::select() helper, and it is expecting an array.
Instead, Laravel has tools built in to do just this. See the lists() method in the Laravel docs under Selects:
public function uploadDocs($userid)
{
$doc_options = DB::table('document')->where('user_id', $userid)->lists('document_description');
return View::make('uploaddocs')->with('doc_options', $doc_options);
}
That should be it.