This is my Route.php
Route::get('users/{user_name}/{source}/{destination}/{members}' , 'Userscontroller#index');
I want array of members in url. How can I get it and How can I pass to index() in UsersController.
Here is my UsersController.php
public function index($user_name, $source , $destination , $members[] )
{
$users = DB::table('users')->insert(array(
'user_name' => $user_name,
'source' => $source,
'destination' => $destination,
));
}
How Can I store array of members in database as well ?
Thank You in Advance.
You can do something like this:
Route::get('users/{user_name}/{source}/{destination}/{members}' , 'Userscontroller#index')->where(['members'=>'.*']);
Then in your controller...
$members = explode("/", $members);
This would let you use a URL like
/users/user_name/source/destination/member1/member2/member3
For storing arrays in databases whilst using eloquent... I've just realised you're not using a Model here but inserting straight into the database, I'd suggest creating a Users model and then you can do this with the below. Otherwise any request for this data you'll need to remember to manually unserialise in whatever format you serialised the data in.
Using attribute casting inside a model (https://laravel.com/docs/5.2/eloquent-mutators#attribute-casting):
Add to the Model:
protected $casts = ['members'=>'array'];
Then you let Laravel do the rest for you:
$users = Users::insert(array(
'user_name' => $user_name,
'source' => $source,
'destination' => $destination,
'members' => $members
));
Related
I'm learning Laravel and have created a public endpoint where I want to output only certain information of some comments if a user is not authenticated from a GET request.
I have managed to filter out the comments based on whether or not they are approved. I now want to filter out the data that is returned. I have attached a screenshot of what is currently returned.
Ideally, I only want to return the id, name and the body in the json. How can I go about this? I tried the pluck() method which did not give the desired results. Any pointers would be greatly appreciated
public function index(Request $request)
{
if (Auth::guard('api')->check()) {
return Comment::all();
} else {
$comments = Comment::where('approved', 1)->get();
return $comments->pluck('id','name','body');
}
}
To select the particular columns, you can pass columns name to get as
$comments = Comment::where('approved', 1) -> get(['id','name','body']);
You can use a transformer to map the incoming data to a sensible output based on the auth state. The following example comes from the Fractal lib:
<?php
use Acme\Model\Book;
use League\Fractal;
$books = Book::all();
$resource = new Fractal\Resource\Collection($books, function(Book $book) {
return [
'id' => (int) $book->id,
'title' => $book->title,
'year' => $book->yr,
'author' => [
'name' => $book->author_name,
'email' => $book->author_email,
],
'links' => [
[
'rel' => 'self',
'uri' => '/books/'.$book->id,
]
]
];
});
Ideally, you would create 2 classes that extend from Transformer and pass the correct one to the output.
If you want to pass the result as json respose
$comments = Comment::where('approved', 1)->pluck('id','name','body')->toArray();
return Response::json($comments);
If you want to pass the result as to blade
$comments = Comment::where('approved', 1)->pluck('id','name','body')->toArray();
return view('your_blade_name')->with('comments',$comments);
I have mysql table 'test' with three columns,
1.sno 2.name 4.country
this code is easily understandable
$person = \App\Test::find(1);
$person->country; //Defined in Test eloquent model
now i want to do something like this:
$p = ['sno' => 1, 'name' => 'Joe', 'country' => '1' ];
$p->country; //Return relevent column form countries table as defined in Model
The thing to remember is that the user i am trying to map is already present in the database table. How to i convert an array to eloquent model?
You could instantiate the model class with no attributes:
$dummy = new \App\Test;
Then you can call the newInstance() method:
$attributes = ['sno' => 1, 'name' => 'Joe', 'country' => '1' ];
$desiredResult = $dummy->newInstance($attributes, true);
The true flag in the method is telling eloquent that the instance already exists in database, so you can continue working with it normally. Now you can do:
$desiredResult->country //'1'
I am using Laravel 5.1
And I need to convert array to diffrent array
So I am having
$wells = Well::get(array('well_id' => 'url','well' => 'name','iso3'))->toArray();
$users= User::get(array('id' => 'url', 'name' => 'name'))->toArray();
So from bouth of the arrays the output should be converted from well_id to url from wells and id to url from users. So even if they are different from the database the output will have the same 'name' because after I am having a function for both but it uses this 'name'.
So the examle I have given is not working but it should be something like this.
Thank you.
You can use select function of Laravel
$wells = Well::select('well_id as url','well as name','iso3')->get()->toArray();
and
$users= User::select(array('id' => 'url', 'name' => 'name'))->get()->toArray();
i haven't try it but it should work.
At the moment I am using the below query:
$claims = ClaimQuery::create('c')
->leftJoinUser()
->withColumn('CONCAT(User.Firstname, " ", User.Lastname)', 'name')
->withColumn('User.Email', 'email')
->filterByArray($conditions)
->paginate($page = $page, $maxPerPage = $top);
However I then want to add columns manually, so I thought this would simply work:
foreach($claims as &$claim){
$claim->actions = array('edit' => array(
'url' => $this->get('router')->generate('hera_claims_edit'),
'text' => 'Edit'
)
);
}
return array('claims' => $claims, 'count' => count($claims));
However when the data is returned Propel or Symfony2 seems to be stripping the custom data when it gets converted to JSON along with all of the superflous model data.
What is the correct way of manually adding data this way?
To export virtual columns to out array you can do it the next way:
/**
* Propel result set
* #var \PropelObjectCollection
*/
$claims = ClaimQuery::create('c')-> ... ->getResults();
/**
* Array of data with virtual columns
* #var array
*/
$claims_array = array_map(function (Claim $claim) {
return array_merge(
$claim->toArray(), // using "native" export function
array( // adding virtual columns
'Email' => $claim->getVirtualColumn('email'),
'Name' => $claim->getVirtualColumn('name')
)
);
}, $claims->getArrayCopy()); // Getting array of `Claim` objects from `PropelObjectCollection`
unset($claims); // unsetting unnecessary object if we have further operations to complete
The answer to this lies in the toArray() method so:
$claims = ClaimQuery::create('c')
->leftJoinUser()
->withColumn('CONCAT(User.Firstname, " ", User.Lastname)', 'name')
->withColumn('User.Email', 'email')
->filterByArray($conditions)
->paginate($page = $page, $maxPerPage = $top)->getResults()->toArray();
Then you can modify as required, the only issue here is that the current toArray method does not return virtual columns so you would have to patch the method to include them. (This is in the PropelObjectCollection class)
In the end I decided to separate the parts:
return array(
'claims' => $claims,
'count' => $claims->count(),
'actions' => $this->actions()
);
This way you do not have to worry about the virtual columns being lost and jut have to manipulate your data in different ways on the other end.
I have a Product model for a multi site application.
Depending on the domain(site) I want to load different data.
For example instead of having a name and description fields in my database I have posh_name, cheap_name, posh_description, and cheap_description.
if I set something up like this:
class Product extends AppModel
{
var $virtualFields = array(
'name' => 'posh_name',
'description' => 'posh_description'
);
}
Then it always works, whether accessed directly from the model or via association.
But I need the virtual fields to be different depending on the domain. So first I creating my 2 sets:
var $poshVirtualFields = array(
'name' => 'posh_name',
'description' => 'posh_description'
);
var $cheapVirtualFields = array(
'name' => 'cheap_name',
'description' => 'cheap_description'
);
So these are my 2 sets, but how do I assign the correct one based on domain? I do have a global function called isCheap() that lets me know if I am on the lower end domain or not.
so I tried this:
var $virtualFields = isCheap() ? $this->cheapVirtualFields : $this->poshVirtualFields;
This gives me an error. Apparently you cannot assign variables in a Class definition like this.
So I put this in my Product model instead:
function beforeFind($queryData)
{
$this->virtualFields = isCheap() ? $this->cheapVirtualFields : $this->poshVirtualFields;
return $queryData;
}
This works ONLY when the data is accessed directly from the model, DOES NOT work when the data is accessed via model association.
There has got to be a way to get this to work right. How?
Well if I put it in the constructor instead of the beforeFind callback it seems to work:
class Product extends AppModel
{
var $poshVirtualFields = array(
'name' => 'posh_name',
'description' => 'posh_description'
);
var $cheapVirtualFields = array(
'name' => 'cheap_name',
'description' => 'cheap_description'
);
function __construct($id = false, $table = null, $ds = null) {
parent::__construct($id, $table, $ds);
$this->virtualFields = isCheap() ? $this->cheapVirtualFields : $this->poshVirtualFields;
}
}
However, I am not sure if this is a CakePHP no no that can come back to bite me?
seems like the issue could be that the model association is a model that is built on the fly. eg AppModel
try and do pr(get_class($this->Relation)); in the code and see what the output is, it should be your models name and not AppModel.
also try and use:
var $poshVirtualFields = array(
'name' => 'Model.posh_name',
'description' => 'Model.posh_description'
);
var $cheapVirtualFields = array(
'name' => 'Model.cheap_name',
'description' => 'Model.cheap_description'
);