I'm working on a old PHP project, that is running in legacy SQL query, which is good but I like to use query builders like Laravel Illuminate SQL package!
So i have added all required package dependencies to run Illuminate SQL, and this query builder seems to work fine with pagination!
$users = Capsule::table('users')->paginate(1)->toArray();
But, the paginator seems not to be able to listen the query string! For example, by running the above code it would give some properties like, next_page , previous_page etc...
And when I try to pass the query string in the URL it can't fetch the data from query string(From the GET request)!
Visiting this page http://app.app/?page=2 would give the same result set.
How i should configure the Illuminate sql package so it can also listen to the query strings?
EDIT
Also, i've tried to use the illuminate/http package, but the $request->all() method always returns an empty array! Here is the code:
<?php
require_once './vendor/autoload.php';
use \Illuminate\Http\Request;
$req = new Request();
echo '<pre>';
print_r($req->all());
echo '</pre>';
It returns empty input data array,
What i am missing to use the http package, any idea would be helpful.
You have to set a page resolver:
\Illuminate\Pagination\Paginator::currentPageResolver(function ($pageName = 'page') {
return (int) ($_GET[$pageName] ?? 1);
});
Laravel uses this resolver.
You need to notice, that paginator won't use other parameters for query string - it just uses page parameter to get valid results page. But for example if you use:
http://app.app/?page=2&price=2
it won't take from database results with price = 2 - it's your job to do this.
However the 2nd thing are urls generated by paginator.
If you do it like this:
$users = Capsule::table('users')->paginate(1);
You can also use in next line
$users->appends(request()->except('page'));
This will add all other parameters from query string (except page) to urls, so first_page_url will then contain all other parameters from request.
You can also wrap it using fluent syntax like this:
$users = Capsule::table('users')->paginate(1)->appends(request()->except('page'));
You need to fetch the query string in the controller to pass the get parameter to
paginate.
You can use the Illuminate\Http\Request class to receive and use the HTTP payload.
Your controller file:
<?php
use Illuminate\Http\Request;
class YourControllerClassName{
public function someFunction(Request $request){
echo "<pre>";
print_r($request->all());
print_r($request->input('page'));
$users = Capsule::table('users')->paginate($request->input('page'))->toArray();
}
}
Related
I have the following url
http://project.su/?invitee=95
first i want to check the invitee in url, if the url have invitee then get the value.
What i have tried (controller) :
if(!empty($request->get('invitee'))){
$user->invitee = $request->get('invitee');
}
The following code is not working .
I want storing the invitee result(id) in database.
Thanks.
To determine if an input value is present:
if ($request->has('invitee')) {
$user->invitee = $request->input('invitee');
}
The has method returns true if the value is present and is not an empty string:
As far as Laravel 5.7 is concerned, the preferred way to retrieve query params is
if( $request->has('invitee') ) {
$request->query('invitee');
}
or using the helper function if you don't have access to $request
request()->query('invitee');
In laravel 5.7, we can also use request()->invitee. By using this, we can get both, URL path parameters and query parameters. Say we have below URL
http://localhost:8000/users/{id}?invitee=95
To read id and invitee, we can use
$id ✔
$invitee ✖ - Invalid
request()->id ✔
request()->invitee ✔
You can get input by:
$invitee = Input::get('invitee');
For above 5.*
$invitee = $request->input('invitee');
Or
$invitee = Request::input('invitee');
To check if invitee parameter exists:
if($request->has('invitee')) {
// ...
}
To get the value of invitee:
$invitee = $request->input('invitee');
Are you calling $user->save() anywhere? You should call $user->save() to actually persist the data.
You can always check by calling dd($user); right after the second line in you example if you are worried it is not set correctly, this way you can see what attributes are set in the $user object.
Also you can replace !empty($request->get('invitee')) with $request->has('invitee').
I am new to Laravel and am building a small project as my schooling. I have struck the above error and I cannot seem to fix it. Any help is appreciated.
In my controller I make the following call when first loading the page. The getDetails method works perfectly on page load, but fails with above error when I call it with Ajax as the user interacts with the page after load.
On page load the method is called and passed to it resulting values from earlier other method calls ($CSpec[0]->id and $CSize[0]->size_mm, which I can see as values 1 and 0.5) as follows:
$CD = CS::getDetails($CSpec[0]->id, $CSize[0]->size_mm);
Also in the controller I have the following function which triggered via a route used in an Ajax call:
public function itemDetails($ct, $cs)
{
return CS::getDetails($ct, $s);
}
The getDetails method looks like this:
public static function getDetails($ct, $cs)
{
return DB::table('recommend_view')
->where('recommend_view.id', '=', $ct)
->where('recommend_view.size_mm', '=', $cs)
->first();
}
I have this route:
Route::get('vd/cd/{cd}/{cs}',
['uses' => 'Application\VDController#itemDetails', 'as' => 'application.vdcdetails']);
When I use Ajax to call the same method it fails with the above error. The Ajax code produces the following url in the $.getJSON call:
http://my.app/vd/cd/1/0.5
If I dd() inside getDetails for each variable I can see the correct values passed to the method from the url / controller.
If I execute the query in MySQL Workbench, it works as expected:
select *
from `recommender_view`
where `recommender_view`.`ct_id` = 1
and `recommender_view`.`cs_size_mm` = 0.50
limit 1;
So the method works perfectly when called on initial page load with variables fed to it directly from other method calls, but when the variables are passed via the URL / Ajax it fails and I cannot seem to understand what the difference is.
UnexpectedValueException in Response.php line 403:
The Response content must be a string or object implementing __toString(), "object" given.
I believe I know what your issue is, however, please feel free to correct me.
What you're using is the Laravel query builder, which returns a stdClass object type in PHP, assuming it finds a result set for your query. This is effectively a "dumb" object that has no methods to "echo" or return. You can't cast to array, nor json etc.
So when the Laravel response object is trying to handle it, it can't use the __toString() method to deconstruct an appropriate response.
What you'd be better off doing is calling the query against a Model that extends the Illuminate Eloquent Model class.
In this instance, it COULD be something like this
CableRecommenderView::where('recommend_view.id', $ct)
->where('recommend_view.size_mm', $cs)
->first();
Eloquent is able to respond accordingly when being passed to the response object.
As an FYI, when using equals ('=') as the comparison operator in queries Eloquent (and possibly the query builder, although you'd have to check on that), you can forego explicitly defining it in the ->where() clause and simply pass the comparison variable as the second argument.
Hope that helps!
The ajax call expects a response to be passed back to it. It is unable to recognize the object you are trying to pass to it.
Look into creating responses http://laravel.com/docs/5.1/responses.
If you return a json response e.g
public function itemDetails($ct, $cs)
{
$item = CS::getDetails($ct, $s);
return response()->json(['data' => $item]);
}
The ajax call should work. Then you can retrieve from the data variable from your ajax.
Consider this code taken from here.
public function getIndex()
{
$posts = Post::orderBy('id','desc')->paginate(10);
// For Laravel 4.2 use getFactory() instead of getEnvironment() method.
$posts->getEnvironment()->setViewName('pagination::simple');
$this->layout->title = 'Home Page | Laravel 4 Blog';
$this->layout->main = View::make('home')->nest('content','index',compact('posts'));
}
As I understand it, pagination limits the number of rows, so I think paginate(10) means select first ten rows in the database. But I absolutely don't understand this.
// For Laravel 4.2 use getFactory() instead of getEnvironment() method.
$posts->getEnvironment()->setViewName('pagination::simple');
or
$posts->getFactory()->setViewName('pagination::simple');
And everything below. Mainly I don't understand what factory means and how it relates to pagination. I went to the laravel docs on Illuminate\Pagination\Factory and Illuminate\View\View but I can't find the meaning of factory. Can anyone explain the code above?
You are essentially setting how the pagination is output in HTML by selecting a specific paginator view, this allows you to have more than one type in an application or use different to the default.
Using multiple pagination types in the same application
Sometimes, you may want to use different pagination types across your
application. By default, Laravel will use the type specified in your
app/config/view.php file, so you need to override this setting when
you wish to use another type. Here is how to do so.
// This code should be in a controller or a route Closure.
// Let’s use the good old example of a list of blog posts.
$articles = Article::paginate(5);
Paginator::setViewName('pagination::simple');
/*
Alternatively, you could also use this to achieve the same result:
$articles->getEnvironment()->setViewName('pagination::simple');
For those who would like to know what’s happening under the hood, here is a more
detailed explanation:
1. Calling paginate() on an Eloquent model or a query builder will return an
instance of \Illuminate\Pagination\Paginator
2. Then, we need to get the related \Illuminate\Pagination\Environment of this
paginator via the well-named getEnvironment() method.
3. Finally, we can specify the pagination type we need. The default value is
'pagination::slider'.
The pagination types that are available by default are located in the
vendor/laravel/framework/src/Illuminate/Pagination/views directory.
*/
Source: http://laravel-tricks.com/tricks/using-multiple-pagination-types-in-the-same-application
I am trying to figure out how to access two (or more) parameters passed to a Laravel controller. I know how to create the route, and the URL is created correctly, but then I can only access the first passed parameter in my controller.
Route:
Route::get('managers/{id}/{parameter2}', array('as'=>'dosomething', 'uses'=> 'ManagersController#dosomething'));
where the first parameter is obviously the $id for managers, and the second parameters is to be processed by the controller.
View:
Do Something
generates the URL:
http://domain/managers/1/2
where 1 is easily accessed as the $id for managers, but when I try to access the 2nd parameter "2" using $parameter2, e.g. using a simple return: "id=$id and parameter2=$parameter2" statement, I get an "unidentified variable: $parameter2" error.
What am I doing wrong?
Is there a better way to pass multiple parameters? I'm especially asking the "better way?" question because what I want to do is use the 2nd parameter to change a value in a database table, and using a 'get' method, somebody could change the parameter value in the URL and therefore cause mischief. Must I use a 'post' method? I'd love to be able to use a link, since that works much better with the design of my application.
Thanks!
I was asked to include the controller, which I'm happy to do. Initially, just for testing, as I mentioned, my controller was a simple return to display the values of the two passed parameters. But here is what I want to be able to do, including the actual name of the function ("update_group" rather than "dosomething") --
ManagersController:
public function update_group($id)
{
DB::table('groups')->where('id','=',$parameter2)->update(array('manager_id'=>$id));
return Redirect::route('managers.show', array('id'=>$id));
}
The update table works perfectly if I replace $parameter2 with an actual value, so that syntax is fine. The issue is that Laravel says that $parameter2 is an undefined variable, despite the fact that the URL contains the value of $parameter2 as you can see above.
And since it occurs to me that the answer to this may involve adding a function to the Manager model, here is the current
Manager.php
class Manager extends Eloquent {
protected $table = 'managers'; ... (mutator and error functions)
}
Just change
public function update_group($id)
to
public function update_group($id, $parameter2)
All looks ok in your route. Seeing the controller code would help, but likely, you may not have a second parameter in your controller's dosomething() method.
public function dosomething($id, $parameter2){
var_dump($id).'<br />';
var_dump($paremter2);
}
If that isn't the case, you can try dumping it from the route's callback to further diagnose.
Route::get('managers/{id}/{parameter2}', function($id, $parameter2)
{
var_dump($id).'<br />';
var_dump($paremter2);
});
Depending on your use case, you can pass them in a query string like so: but it isn't really the 'best way', unless you're doing something like building an API that won't use the same variables in the same order all the time.
/managers?id=1¶mter2=secondParameter
var_dump(Request::query('id')).'<br />';
var_dump(Request::query('paramter2'));
Controller:
public function getSpecificPost($id)
{
$returnArray = with(new Posts)->getSpecificPost($id);
print_r($returnArray);
}
?>
Model:
public function getSpecificPost($post_id)
{
//exit($post_id);
return DB::table('posts')->where('id', $post_id)->toSql();
}
?>
If I uncomment the exit, it gives me a 1 as return.
When I comment the exit I of course get a query, the query is as follows:
select * frompostswhereid= ?
Its Laravel Framework, help me out please!
The ? is a placeholder for your variable. It will be replaced with (in this case) 1. See the colored block on this page:
Note: The Laravel query builder uses PDO parameter binding throughout
to protect your application against SQL injection attacks. There is no
need to clean strings being passed as bindings.
You are aware of the fact that your don't actually execute the query? If you want to get the specific post with $post_id, you can change the line in your model to this one:
return DB::table('posts')->where('id', $post_id)->first();
If you want to see all executed queries (with replaced variables!) with Eloquent, you can use Laravel PHP Debugbar.