How to put plural parameters into url with laravel - php

I want to build a website with a plural levels in the url. When it gets deeper,I find it difficult to get the parameters in the url.For example, www.example.com/level1/level2, I can get plural parameters level2(plural pages) because I know level1,but as it keeps going like level1/level2/level3,since parameter level2 is unknown value,how should I get level3? Because based on what I'm thinking, there are level4 and level5, at last, should the route file look like Route::get('/{parameter1}/{parameter2}/{parameter3}/{parameter4}','Controller#func')?
Any reply will be appreciated!

Is this what you are looking for?
{{ url('func', ['level1' => 'val1', 'level2' => 'val2', 'level3' => 'val3']) }} // your link
Route::get('/func', 'YourController#func');
your action method
public function func(Request $request){
$level3 = $request->get('level3');
}

Related

Laravel - Cannot Access Collection Indexes

For sure it's an understanding issue on my part. I'm just trying to create a collection in which the elements can be output.
Example:
So I want to be able to execute:
$collection=collect([
'index1' => 'data1',
'index2' => 'data2',
'index3' => 'data3',
]);
$row=$collection->first();
dd($row->index1);
Or similar.. But I get the error
trying to get property of a non object.
It's an understanding issue about Laravel collections, I've read the Laravel documentation which goes from basic usage, to API reference. I cannot find the information on how to produce this basic static collection.
Can someone help?
$row=$collection->first(); points to the value data1, not an object/array.
To get the expected behavior try the code below, it wraps each in individual arrays.
$collection=collect([
['index1' => 'data1'],
['index2' => 'data2'],
['index3' => 'data3'],
]);
$row=$collection->first();
dd($row->index1);
As Laravel collections implement ArrayAccess you can simply access collection items as you do with an array
$value = $collection['index1'];
or you can use the get method on collections
$value = $collection->get('index1');
Thanks for your answers, I see the $collection['index1']; format works.
It's not exactly what I wanted, let me explain why. I know there's probably a better way of doing it although, for the sake of this particular coding requirement I'd like to know the answer to this.
I'm building a CRUD blade form.
On my blade I'll have 'field1' with initial output of $dbcollection->field1
Now of course if the database returns a null (create required) this output will fail. So what I'm trying to do here is pass blade a NULL-filled collection it understands so at least it doesn't complain about non instance of an object and avoiding #if statements on the blade form to account for differences in coding format.
I believe this is what you are looking for:
Controller:
$collection=collect([
'index1' => 'data1',
'index2' => 'data2',
'index3' => 'data3',
]);
$row = $collection->first();
view:
<input type="text" value="{{ ($row->index1 ? $row->index1 : '') }}" >
.
.
.
.

Laravel append URI in route

Hi I want to append the uri in laravel route function.
e.g we have /search?type=listing
//how do i can achieve this with
route('search',['type'=>'listing'])
Once the we are on the search. I want to have all the variable appended to search like
type=listing&query=blah blah
If I get you right, you want to save all query parameters. Use Request::query() to get it and then merge with your new parameters.
route('search', array_merge(\Request::query(), ['type' => 'listing'])));
If you have a named route and want to generate url with query params then:
route('route_name', ['param1' => 'value', 'param2' => 'value']);
In your case you can do this with
route('search',['type'=>'listing','subject' => ['blah'],[....]])

A better way to re-use a boilerplate search parameter across controller actions

How do I re-use boilerplate query code across multiple controller actions in CakePHP 2.4?
I've got some join code I need to re-use across multiple actions, which excludes all Posts which belong to a Project where Project.published = 0 from my find(). I've done this by creating a public class array to hold the query code.
This works, however I'd like to add some additional parameters based on variables- specifically, allowing the owner of a Project to see data belonging to their project, even if it's unpublished.
If the array were integrated as part of the controller action, I'd simply add 'ProjectAlias.user_id' => CakeSession::read("Auth.User.id") to the final OR array below. However, I can't include that as part of a class array, and I need to create it in the action, as seen below.
This doesn't feel especially elegant. Is there a cleaner / more Cake way to handle this?
My current code:
//==============
// ADDITIONAL JOIN TO RESTRICT RESULTS TO LIVE PROJECTS
//================
public $joins = array(
array(
'table' => 'projects',
'alias' => 'ProjectAlias',
'type' => 'right',
'conditions' => array(
'OR' => array( // One of these two things:
'Post.project_id' => null, // Posts with no project
'AND' => array( // And posts with a Project that is published.
'Post.project_id = ProjectAlias.id',
'OR' => array(
'ProjectAlias.published !=' => 0,
)
)
)
),
)
);
//===============
// Example function showing how this array is used. There are four in all
// so repeating the above code would get to be too much.
//================
public function example() {
// Let project leads see data from their hidden projects, by modifying the array.
// This doesn't seem very elegant!
$this->joins[0]['conditions']['OR']['AND']['OR'][] = array(
'ProjectAlias.user_id' => CakeSession::read("Auth.User.id")
);
// Use the array
$this->paginator->settings['joins'] = $joins;
$this->set('posts', $this->Paginator->paginate());
}
If I understood it right, you can create a function which requires arguments in AppController which returns the join array & call it from any actions of any controllers. Now, regarding different params for different cases, first you can use-
$this->request->action
to get the current action (or controller as well if needed).
Now, you can set an associative array or if else block in the function in AppController to define the join array, using function arguments as required. Then you can get custom made $joins array from any actions.

Symfony sfWidgetFormDoctrineChoice with multiple option on

I have created a form in which i embed another form. My question is about this embedded form - I'm using a sfWidgetFormDoctrineChoice widget with option multiple set to true. The code for this embedded form's configure method:
public function configure()
{
unset($this['prerequisite_id']);
$this->setWidget('prerequisite_id', new sfWidgetFormDoctrineChoice(array(
'model' => 'Stage',
'query' => Doctrine_Query::create()->select('s.id, s.name')->from('Stage s')->where('s.workflow_id = ?', $this->getOption('workflow_id') ),
'multiple' => true
)));
$this->setValidator('prerequisite_id', new sfValidatorDoctrineChoice(array(
'model' => 'Stage',
'multiple' => true,
'query' => Doctrine_Query::create()->select('s.id, s.name')->from('Stage s')->where('s.workflow_id = ?', $this->getOption('workflow_id') ),
'column' => 'id'
)));
}
I unset the prerequisite_id field because it is included in the base form, but I want it to be a multiple select.
Now, when I added the validator, everything seems to work (it passes the validation), but it seems like it has problems saving the records if there is more than one selection sent.
I get this PHP warning after submitting the form:
Warning: strlen() expects parameter 1 to be string, array given in
D:\Development\www\flow_dms\lib\vendor\symfony\lib\plugins\sfDoctrinePlugin\lib\database\sfDoctrineConnectionProfiler.class.php
on line 198
and more - I know, why - in symfony's debug mode I can see the following in the stack trace:
at Doctrine_Connection->exec('INSERT INTO stage_has_prerequisites
(prerequisite_id, stage_id) VALUES (?, ?)', array(array('12', '79'),
'103'))
So, what Symfony does is send to Doctrine an array of choices - and as I see in the debug sql query, Doctrine cannot render the query correctly.
Any ideas how to fix that? I would need to have two queries generated for two choices:
INSERT INTO stage_has_prerequisites (prerequisite_id, stage_id) VALUES (12, 103);
INSERT INTO stage_has_prerequisites (prerequisite_id, stage_id) VALUES (79, 103);
stage_id is always the same (I mean, it's set outside this form by the form in which it is embedded).
I have spend 4 hours on the problem already, so maybe someone is able to provide some help.
Well, I seem to have found a solution (albeit not the best one, I guess). Hopefully it'll be helpful to somebody.
Finally, after much thinking, I have concluded that if the problem comes from the Doctrine_Record not being able to save the record if it encounters an array instead of a single value, then the easiest solution would be to overwrite the save() method of the Doctrine_Record. And that's what I did:
class StageHasPrerequisites extends BaseStageHasPrerequisites
{
public function save(Doctrine_Connection $conn = null)
{
if( is_array( $this->getPrerequisiteId() ) )
{
foreach( $this->getPrerequisiteId() as $prerequisite_id )
{
$obj = new StageHasPrerequisites();
$obj->setPrerequisiteId( $prerequisite_id );
$obj->setStageId( $this->getStageId() );
$obj->save();
}
}
else
{
parent::save($conn);
}
}
(...)
}
So now if it encounters an array instead of a single value, it just creates a temporary object and saves it for each of this array's values.
Not an elegant solution, definitely, but it works (keep in mind that it is written for the specific structure of the data and it's just the effect of my methodology, namely See What's Wrong In The Debug Mode And Then Try To Correct It Any Way Possible).

How to implement pagination using multiple searcing criteria in codeigniter

Im trying to implement pagination using multiple searching criteria.
Supposed I Have student table. I also use pagination when the list of student displayed.
The pagination link is. site_url . '/student/page/'; so I use $config['uri_segment'] = 1;
so the pagination link will be
1
2
and son.
After that I wanna search student data using 3 searching criteria implemented using textfield.
id name address.
user can search by id or name or address or combination of the three criteria.
the url become
http://mysite/index.php/student/page/0
href=http://mysite/index.php/student/page/1
and son.
but I use get method for searching. and while trying to search using the search criteria field the url become
href="http://mysite/index.php/student/page/1?id=1&name=a&address=b
the problem occurred when I try create pagination based on criteria. because the pagination link have contain query string
i don't know how to create become
href="http://mysite/index.php/student/page/0?id=1&name=a&address=b
href="http://mysite/index.php/student/page/1?id=1&name=a&address=b
or do you have a best practice to solve this problem ?
To solve that problem, I try using $this->uri->uri_to_assoc(). First I create array asocc for pagination link.
$array = array('id' => '001', 'name' => 'a', 'address' => 'canada');
the url become
id/001/name/a/address/canada. I use $this->uri->uri_to_assoc() function to get key and value of the segment.
array (
id => 001,
name=>a,
address=>canada
)
but while there some searching criteria that not included while searching. let say, the user only search by name and address. the array become
$array = array('id' => '', 'name' => 'a', 'address' => 'canada'); and the url id/name/a/address/canada
the assoc array become
array (
id => name,
a=>address,
canada=>
)
the assoc array is not disorganized again. so I can't get the right value of the assoc array.
I think i will set the identifier to the searching criteria if not included. supposed i put #.
if isset($_GET['id']) then
$id = '#'
else
$id = $_GET['id']
$array = array('id' => $id, 'name' => 'a', 'address' => 'canada');
How about that ... ? or if there are another best practice ?
Thanks
I've always found it somewhat a pain to deal with uri's in ci.
Is there a way you can set a default of some kind for your values if the user doesn't include that as part of their search? or even not include the key? so it would return something like
id/10/name/false/address/canada
or
id/10/address/canada
then you can
$uri = $this->uri->uri_to_assoc();
$id = array_key_exists("id", $uri) ? $uri['id'] : false;
$id = $id == 'false' ? false : $id;
$query .= $id ? "AND id = $id" : "";
etc...
When I use uri_to_assoc, I always have a default array, so in my application, I can always get the required parameter, even if it missing from the uri
$param_default = array('cat','page');
$param_array = $this->uri->ruri_to_assoc(3, $param_default);
Now I can safely access $param_array['cat'] and $param_array['page'] even when uri doesn't contain that parameter.
I always user ruri_to_assoc and ruri_segment, so the extra parameter always start in 3rd uri segment.

Categories