Is it possible to make an API which prints database records like this: http://localhost:8000/products/?compare=1-2-N...(1,2,N) product id's. I have succeeded printing only one record. My route:
$router->get('products/{id}','ProductController#getProduct');
and my controller:
public function getProduct($id){
$tlt_products = DB::table('tlt_products')->find($id);
$tlt_products_features_id = DB::table('tlt_product_features')->where('product_id', $id)->get()->pluck('feature_id');
$tlt_features = DB::table('tlt_features')->whereIn('id', $tlt_products_features_id)->get()->groupBy('feature_group');
$tlt_feature_groups = DB::table('tlt_features')->groupBy('feature_group')->get()->toArray();
return response()->json([
'product' => $tlt_products,
'product_features' => $tlt_features,
'feature_groups' => $tlt_feature_groups
]);
}
could you please help me printing array of records using route like this:
http://localhost:8000/products/?compare=1-2-3...-N
Yes, it can be possible. You can try to pass a pattern through get and parse it to retrieve the information your need, but why don't you use a simple way to do that such as:
$router->get('products/{begin}/{end}','ProductController#getProduct');
every thing you want it possible just design it well and in your controller, you have
public function getProduct($begin,$end){
...
}
I finally managed to solve this issue using $tail = $request->tail;method and adding requested id like this on my form action
#php
$tail = basename(request()->path());
$text = (string)$tail;
#endphp
<form action="/product-compare/{{$text}}-{{ $product['id'] }}" method="post">
Related
I'm using select2 jquery plugin, and laravel form model binding to render the data from the server.
While everything else works fine, it doesn't rendered the tags that has been attached to the post as selected option.
there must be something which I'm unaware of, here's my view part.
<div class="form-group">
{!! Form::label('tag_list','Tags:') !!}
{!! Form::select('tag_list[]', $tags,null,['id'=>'tag_list', 'class'=>'form-control','multiple']) !!}
</div>
// This is the select 2 script
$('#tag_list').select2({
'placeholder':'Choose Tags',
tags:true,
tokenSeparators:[",", " "],
createTag:function(newTag){
return{
id:'new:' + newTag.term,
text:newTag.term + '(new)'
};
}
});
And this is a getTagListAtrribute function in Article model
// This is the getTagListAttribute function
public function getTagListAttribute(){
return $this->tags->lists('post_id')->all();
}
And I load the edit form from the controller like this:
public function article_edit($slug){
// fetch the articles.
//$article = DB::table('articles')->where('slug',$slug)->first();
$article = Article::where('slug',$slug)->first();
/*echo '<pre>';
print_r($article->title);
die();*/
$tags = DB::table('tags')->lists('name','tag_id');
$categories=DB::table('categories')->lists('category_name','category_id');
return view('admin.pages.edit', compact('article','tags','categories'));
}
I just want the tags which are associated with article be selected while the page loads, and which I've been unable of. So I'm in the need of help.
Well, since you have tagged the question as laravel-5.1. There are some changes been made to the lists method.
In Laravel 5.0.* it returned just the plain array of keys and/or values that you pass in the lists method. More info here
In Laravel 5.1.*, it returns a Collection object. More Info - Just the code documentation
So, the solution that you are looking for is:
In controller, do this:
$tags = DB::table('tags')->lists('name','tag_id')->toArray();
Or in the view file, do this:
{!! Form::select('tag_list[]', $tags->toArray(), null,['id'=>'tag_list', 'class'=>'form-control','multiple']) !!}
And that should do the trick for you.
EDIT 1:
Remove all() method from getTagsListAttribute(). That is not at all required.
Why are you using DB Facade for querying the tags table ? Since you have already established the relationship, you are unnecessarily executing the SQL Statements. Avoid that as much as you can.
You should get it by simply doing this:
$tags = $article->tags;
EDIT 2:
Are you sure that you have tag_id column in tags table ? I doubt that. I guess that must be a typo.. By mistakenly, you must have typed tag_id instead of id. Cross verify it for the confirmation.
Hope this helps you out. Happy Coding. Cheers.
Set select form tag like this
{!! Form::select('tag_list', $tags, $selected, ['id'=>'tag_list', 'name'=>'tag_list[]','class'=>'form-control','multiple']) !!}
Pass the ids to be selected as array in third ($selected).
So, if
$tags = ['1'=>'one', '2'=>'Two', '3'=>'Three']
and you want One and Three selected, pass these ids as an array to the form select as the third parameter.
so, $selected = [1,3];
struggling to figure out how to best do what I would normally in simple PHP.
I have the following URL:
/viewbuild/2
The aim is that viewbuild is the view and 2 is the id of the database row.
Normally It would simply be:
$id = $_GET['id'];
But cant figure out to do it PROPERLY using laravel.
This is my route:
Route::get('viewbuild', function()
{
return View::make('viewbuild');
});
And on my view I have done e.g.:
<?php
$build = Build::find(20);
?>
{{ $build->id }}
This correctly searches the builds table for a row with the id of 2 and then displays its id.
What I now want to do is pull the '20' value from the URL.
I have tried:
Route::get('/viewbuild/{build_id}', function($build_id = null)
{
$data = array(
'build_id' => $build_id,
);
return View::make('viewbuild', $data);
});
And then on my view:
$build = Build::find(build_id);
But I get undefined constant errors.
Any help on this?
Basically i can see two things from quick looking at your code:
A typo when setting the array to be passed to the view build_ud should be build_id i presume
You are referencing a constant for the build_id (no $ sign) in your view instead of the passed variable which is passed to the view. Ie:
$build = Build::find(build_id);
should be:
$build = Build::find($build_id);
Your route closure should look like this:
Route::get('/viewbuild/{build_id?}', function($build_id = null)
{
// Query the database here instead of inside the view
$build = Build::find($build_id);
return View::make('viewbuild', compact('build'));
});
I have to create a form for a set of models, but unfortunately, I don't know how to do.
My first idea is to create a single form and a controller action which renders the view containing the form. But, this idea let me face an error. I create an action like this :
public function actionAddInfo($id){
$participant = Participant::model()->find('id_participant = ' . $id);
$info = InfoComp::model()->findAll('id_event = ' . $participant->id_event);
// here I must save the model if submitted
$this->render('addInfo', array('model' => $info));
}
In fact, the relationship in my models Participant, Evenement is below :
'idEvent' => array(self::BELONGS_TO, 'Evenement', 'id_event');
When accessing the variable $info in the view,
echo count($info);
I got the exception :
Undefined variable $info
This exception let me ask whether it is possible to proceed like that. I need your help. Else, can somebody suggest me another way to proceed ?
You are sending the variable with name model and you are trying to access it with name $info..
All you need to change is this:
$this->render('addInfo', array('info' => $info));
I’m trying to implement a simple search into an application, but not sure of the best way to handle this. My database contains a Listings object which includes City field. I want to create a search form where the user inputs a city into a text field and gets all of the Listings for that city on the next page. I don’t want to perform a full-text search, just the query on that City field.
Also, on the results page, I’d like to store the query in POST and can’t figure out the best way to do this.
What is the best way to approach this in the controller?
Well your view would look something like this
$this->Form->Create('Listing', array('action'=>'search'));
$this->Form->input('city', array('default'=>$city));
$this->Form->end();
if (isset($listings)) {
//code to display listings
}
This view would create the correct form. And your controller needs to get that value
function search() {
$city = '';
if (!empty($this->data)) {
$city = $this->data['Listing']['city'];
$opts = array(
'conditions' => array('Listing.city' => $city)
);
$listings = $this->Listing->find('all', $opts);
$this->set('listings', $listings);
}
$this->set('city', $city); // so the keyword is saved. Can also get it via $this->data
}
This code should give you an idea on how to do this.
This is a great tutorial with a CakePHP search plugin tutorial. You can download the full working code as well from github (w/ MySQL dump).
View:
<?php echo $this->Form->create()
echo $this->Form->input('search');
?>
<input name="data[Product][word]" />
controller:
<?php
$result = $this->Product->find('all',array(
'conditions'=>array(
'OR'=>array(
array('name LIKE'=>'%'.$word.'%'),
array('description LIKE'=>'%'.$word.'%')))));
$this->set(compact('result'));
?>
I need to make a simple site search with pagination in it; could anyone tell me how to do it without affecting the URL structure? Currently I'm using the default CodeIgniter URL structure and I have removed index.php from it. Any suggestions?
You could just use a url like /search/search_term/page_number.
Set your route like this:
$route['search/:any'] = "search/index";
And your controller like this:
function index()
{
$search_term = $this->uri->rsegment(3);
$page = ( ! $this->uri->rsegment(4)) ? 1 : $this->uri->rsegment(4);
// some VALIDATION and then do your search
}
Just to update this question. It is probably best to use the following function:
$uri = $this->uri->uri_to_assoc()
and the result will then put everything into an associative array like so:
[array]
(
'name' => 'joe'
'location' => 'UK'
'gender' => 'male'
)
Read more about the URI Class at CodeIgniter.com
Don't quite understand what you mean by "affecting the url structure". Do you mean you'd want pagination to occur without the URL changing at all?
The standard pagination class in CI would allow you to setup pagination so that the only change in the URL would be a number on the end
e.g if you had 5 results to a page your urls might be
http://www.example.com/searchresults
and then page 2 would be
http://www.example.com/searchresults/5
and page 3 would be
http://www.example.com/searchresults/10
and so on.
If you wanted to do it without any change to the URL then use ajax I guess.
Code Igniter disables GET queries by default, but you can build an alternative if you want the url to show the search string.
Your url can be in the notation
www.yoursite.com/index.php/class/function/request1:value1/request2:value2
$request = getRequests();
echo $request['request1'];
echo $request['request2'];
function getRequests()
{
//get the default object
$CI =& get_instance();
//declare an array of request and add add basic page info
$requestArray = array();
$requests = $CI->uri->segment_array();
foreach ($requests as $request)
{
$pos = strrpos($request, ':');
if($pos >0)
{
list($key,$value)=explode(':', $request);
if(!empty($value) || $value='') $requestArray[$key]=$value;
}
}
return $requestArray ;
}
source: http://codeigniter.com/wiki/alternative_to_GET/