Getting variable passed in URL with Laravel 4 - laravel

I want to get the ID which was passed in the URL but it seems something goes wrong!
This is my routes.php
Route::get('/poste/{idp}',array('before' => 'members_auth',function($id){
//dd($id);
$post =Posts::where('idp','=',$id) -> get();
$titre=$post->titre;
$desc=$post->description;
return View::make('showPost',array('title'=>$titre,'description'=>$desc));
}));
And this is my View
<a href="/poste/{{$userpost->idp}}">
The error was Undefined property: Illuminate\Database\Eloquent\Collection::$titre

It is quite common issue when you start with Eloquent ORM. Basically get() method always returns Collection of objects, even if there is only one found. Sure enough Collection object has no titre property. If idp is primary key for your Post model, you should use find() or findOrFail() method instead.
$post = Posts::find($id);
As Laravel documentation states:
Note: Eloquent will also assume that each table has a primary key
column named id. You may define a primaryKey property to override this
convention. Likewise, you may define a connection property to override
the name of the database connection that should be used when utilizing
the model.
You are free to override your primary key.
class Posts extends Eloquent
{
protected $primaryKey = 'idp';
}

Related

Join multiples fields from different tables with Laravel Model

i try return multiples fields from different tables in just one request, example
properties table
-id
-name
-address
rules table
-id
-checkin
-propertyId
i hope a response just like that
[
id=>123,
name=>Name,
address=>Main Street,
checkin:10:00
]
And i would like that this can be used by default in all futures request, all(), first(), get()
Note: I can't use relationship because I need to join two tables in just one
Simple solution set the default with on the property class to include the rule.
protected $with = ['rule'];
To fill you exact spec, add a checkin getter on the property model and use the append property to add it to the serialization.
protected $appends = ['checkin'];
public function getCheckinAttribute()
{
return $this->rule->checkin;
}
Extending the query builder
Laravel Eloquent Query Builder Default Where Condition
Applying logic for all your model queries
Or for the default scope
You could do it this was
https://laraveldaily.com/model-default-ordering-assigning-global-scope/

Laravel Eager-loading works only when calling attribute

I've defined my Slot model to load the relations from User model like so :
public function userAssignedFull(): HasOne {
return $this->hasOne(User::class,'id','user_assigned');
}
('slots' table contains 'user_assigned' field by which I connect to User records on 'id')
The following code finds Slot model but without 'userAssignedFull'. I get only the user ID in 'user_assigned'.
$slot = Slot::with('userAssignedFull')->find($slot_id);
But calling this afterward returns me the wanted relation:
$fullUserModel = $slot->userAssignedFull;
Can anyone tell me what am I doing wrong ?
Builder::with() returns the Builder instance.
So you have to call $slot->userAssignedFull; to get the collection of data.
From the docs:
When accessing Eloquent relationships as properties, the relationship
data is "lazy loaded". This means the relationship data is not
actually loaded until you first access the property.
And this $slot->userAssignedFull; is your "first access the property".
Try this
$slot = Slot::where('id', $slot_id)->with('userAssignedFull')->first();
$slot->userAssignedFull;

Laravel, related model reuturened names

I have a model that has a related model
class A extends Model{
public function niceName()
{
return this->hasOne('App\NiceName2' ...);
}
In the controller when I retrieve data with submodel the result is like
a[nice_name_2] (using the table name) and I would like it to be a[NiceName2].
Is there a way to have an alias for the returned result? In cakePHP i know there is propertyName to set this on relations. Laravel has a similar feature?
Thanks
Laravel uses the convention of camelCase for method names and snake_case for attributes. I'm not sure there's an easy way around this.
When Laravel serializes the data, it converts relationships to snake_case, by convention. So NiceName2 would become nice_name2 when you execute toArray() or when the model is serialized (either in a JSON response or otherwise).
How this works is:
When you access $model->nice_name2 it converts the property name back to niceName2 to check for a relationship method with that name. When serializing, it converts the relationship niceName2 to the attribute name nice_name2.

Laravel 5 - Limiting Eloquent Where Parameters When Using Request Object Data For Get

I have controller functions that look like:
public function get(Request $request){
return json_encode($this->users->get($request->all));
}
where $this->users references a repository for my User model. Inside of this repository, I have a function that looks like:
public function get($request){
return User::where($request)->get()->toArray();
}
I can dynamically pass in any number of parameters to search on through my HTTP request with the above code without having to explicitly state the column names.
This works well as long as all the parameters passed in through the request are valid column names. It will error out if I pass in a parameter that is a not valid table column.
I have the protected $fillable array defined in each of my models corresponding to my repositories.
Is there anyway to enforce what can be passed into the where() method above so that only valid columns defined in the $fillable array in my model are ever passed in?
For example, let's say I have a users table with columns (id, name, description). The GET URL I pass in looks like:
GET /user?name=mike&description=skinny&age=45
There are three parameters in the URL above, but only two of them are valid column names. I would like the age parameter to be automatically taken out. In my current code, the above URL will return an error response since the age column does not exist.
You can use array_only() helper:
return User::where(array_only($request, $this->fillable))->get()->toArray();
It will filter $request and will keep only key/value pairs which are in the $fillable array.
If this code is not in a model, change $this->fillable to appropriate variable or method call.
I wrote a package for doing this kind of filtering for models. It will allow you to filter based on User::filter($request->all())->get(); while defining each possible column's where() constraint.
https://github.com/Tucker-Eric/EloquentFilter
Try doing something like this:
public function get(Request $request)
{
$user = new User();
return User::where(
$request->only($user->getFillable())
)->get()->toArray();
}
By creating an instance of User you can then access it's fillable properties using getFillable(). By passing this list into $request->only(...) you can restrict the values you pull out to only those that are in your fillable array. Hopefully that should mean only fillable values are considered as part of your query.
Hope it helps.

'Method' vs 'Dynamic Property' in Eloquent ORM with Laravel?

I want to count the number of posts belongs to a tag. Should I use method or dynamic property?
<?php
class Tag extends Eloquent {
public function posts()
{
return $this->belongsToMany('Post');
}
public function postsCount()
{
return count($this->posts);
}
public function getPostsCountAttribute()
{
return count($this->posts);
}
}
So in template should I use dynamic property:
{{ $tag->postCount }}
or method:
{{ $tag->postCount() }}
Excerpt from the documentation of Laravel 4 regarding Eloquent's Dynamic Properties (accessor) in relationships (bold are mine):
Eloquent allows you to access your relations via dynamic properties. Eloquent will automatically load the relationship for you, and is even smart enough to know whether to call the get (for one-to-many relationships) or first (for one-to-one relationships) method. It will then be accessible via a dynamic property by the same name as the relation.
That said, using the method defined for the database relationship or the dynamic property (accessor) will behave differently.
If you issue the post count using the method as follows:
$count = $tag->posts()->count();
That will generate the proper SQL with the COUNT aggregate function.
In the other hand, if you issue the post count using the dynamic property (accessor) as follows:
$count = count($tag->posts);
That will fetch all the posts, convert them to an array of objects, then counting the number of element of the array.
In your case, the choice should depend of the usage of the posts related to a tag. If you just want to count, then use the method and the aggregate function. But, if apart from counting you will be doing something else with those posts, then use the dynamic property (accessor).

Resources