w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Multipart response in Laravel 4
You want a mulipart form, don't you? echo Form::open(array('url' => 'foo/bar', 'files' => true)) From http://laravel.com/docs/html

Categories : PHP

Including additional custom attributes in an laravel eloquent response
I would go at this the other way. In your Users model... public function profile() { return $this->belongsTo('Profiles','profile_id'); } Then you can use $profile = User::find(user_id)->profile. $data = array( 'id' => $profile->id, 'url' => "/profile/".$profile->city_slug."/".profile->slug ); And then finally return Repsonse::json($data,200);

Categories : Laravel

Laravel dynamic property not working
You need to eager load the relationship. Level::with('lessons')->find(1)->lessons; should work. If you want to load this relationship every time, you should add this line to Level model. protected $with = array('lessons');

Categories : PHP

Laravel 4 - Dynamic Routing/Views
I would personally choose to do this logic in it's own filter rather than the Route Group closure, since what you are doing is simply 'filtering' users to different routes depending on variables (same thing an Auth filter does). update Route::filter('whatever', function() { $teamUser = php_sapi_name() == "cli" ? null : @TeamUser::find(Session::get('credentials.team')); if ( empty($teamUser) ) Redirect::route('IndexController'); }); Route::group(array('before' => 'auth|whatever', function() { Route::controller('someController'); Route::controller('/', 'IndexController'); }));

Categories : PHP

ASP.NET MVC format a JSON response from a dynamic
What I am essentially looking for guidance on is how to flip it out so it reads: [ {"date":"/Date(1331683206000)/","Variable1","ValueX"}, {"date":"/Date(1331683206000)/","Variable2","ValueY"}, {"date":"/Date(1331683206000)/","Variable3","ValueZ"} ] I am afraid that this is impossible because your desired output is an invalid JSON. If you meant this: [ ["/Date(1331683206000)/","Variable1","ValueX"], ["/Date(1331683206000)/","Variable2","ValueY"], ["/Date(1331683206000)/","Variable3","ValueZ"] ] then this is an entirely different matter. UPDATE: After showing your actual desired JSON you could project your result in order to achieve it: IEnumerable<dynamic> result = .... var viewModel = result.Select(x => { var result = new Dictionary<

Categories : C#

Laravel Error: The Response content must be a string or object implementing __toString(), "boolean" given
Looks like you are authenticating users. Why not use Laravel's authentication that is offered to you out of box? For you code, not sure if it's the chained withInput() causing the error, anyway I am strongly against chaining withErrors and withInput, for it will be problematic. A better approach is to use Input::flash(); See the doc

Categories : PHP

'Method' vs 'Dynamic Property' in Eloquent ORM with Laravel?
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, i

Categories : Laravel

Dynamic Search using getJSON in jQuery and Laravel 4
You don not register the right URL. Two ways of solving this problem & wrote a little code for better understanding (tune it to your needs) 1. Adjust PHP // Here, modified URL Route::get('searchpeeps', function(){ return Input::get('q'); }); Using this Javascript $(".searchterm").keyup(function(e){ $.getJSON( "searchpeeps", { q: this.value }, function(data) { console.log(data); } ); }); 2. Adjust Javascript $(".searchterm").keyup(function(e){ $.getJSON( "searchpeeps/" + this.value, null, function(data) { console.log(data); } ); }); ... with this PHP Route::get('searchpeeps/{q}', function($q){ return $q; });

Categories : Laravel

Laravel 4 dynamic route with multiple segments
I believe one complication when using Route::get('{slug1}/{slug2}', 'PagesController@index'); would be handling all possible inputs so segment1/segment2/ and also foo/bar/. You would probably end up with lots of unnecessary logic. This may not be the best solution but I believe groups would work well for what you are trying to accomplish. Route::group(array('prefix' => 'segment1'), function() { Route::get('/', 'ControllerOne@index'); Route::group(array('prefix' => 'segment2'), function() { Route::get('/', 'ControllerTwo@index); Route::get('/segment3', 'ControllerThree@index'); }); }); Maybe a little messy when only dealing with three examples but it could end up being beneficial and provide a nicer hierarchy to work with. This also has the benefit

Categories : PHP

Laravel 4 Dynamic Query Being Output Wrong
The LIMIT keyword and rowcount is missing in the query. That syntax is invalid. The query should be something like: ... DESC LIMIT 2 OFFSET 0 The OFFSET keyword is part of the LIMIT clause, it can't appear just by itself. It's not at all clear why Eloquent is generating that, since it isn't valid SQL. Followup: Verify that $number_of_posts evaluates to a non-negative integer, so that a valid LIMIT clause can be generated. If $number_of_posts contains something other than a valid value for LIMIT, it's unlikely that it would generated invalid SQL. (It looks like the error in the query builder is generating a statement that includes OFFSET without a corresponding LIMIT.

Categories : PHP

Pipe with dynamic request/response type?
You can't do it quite the way you asked, but you can cheat a little bit and get something that's almost as good: {-# LANGUAGE ExistentialQuantification #-} module Toy where import Control.Monad import Pipes import Pipes.Prelude (foreverK) data Request = forall a . Request [a] (a -> String) asker :: Monad m => () -> Client Request Int m () asker () = do _ <- request (Request [0.0, 2.0] show) _ <- request (Request ["3", "4"] show) return () server :: Request -> Server Request Int IO r server = foreverK $ eq -> case req of Request as f -> do choice <- lift $ do let select = do putStrLn "Select an option" forM_ (zip [0..] as) $ (n, a) -> putStrLn $ show n ++ ": " ++ f a

Categories : Haskell

Laravel 4 dynamic menu: "Route::is('users/*')" not working
are you sure the right method to use is Route::is? I can't see this mentioned anywhere in the code. It's quite possibly you're looking for Request::is, ie: Request::is('users/[a-z]*') This deeper down utilizes the Str::is() function, which takes the same argument, and I'm not sure if * applies there, which is why I've given the full regular expression in this example. You can try with just using * instead of the [a-z] match as well, and see if that works.

Categories : PHP

Laravel 4 Eloquent ORM accessing one-to-one relationship through dynamic properties
Ok so the problem had to do with using underscores in the class names. Laravel follows PSR 0 and 1 as outlined here. What this means is I had to name my model class and filename UserProfile (even though my MySql table named remained 'user_profiles'), and then update my User model to have a function called userProfile(). Once I updated the naming, I could access the relationships automatically by doing something like: $user = Auth::user(); echo $user->userProfile->first_name;

Categories : Laravel

Response mapping to get object with dynamic path restkit
If you have 2 path patters which both return the same type of data then you can use the same mapping with 2 different response descriptors. If you have 1 path pattern which can return 2 different types of data then you need to use RKDynamicMapping to 'intercept' the incoming data and decide which mapping is actually required. From your edited question, 'pattern' is the important thing that you have misunderstood. You need to use a path pattern, not a static path: @"getAllCategories/:identity"

Categories : IOS

Laravel Response::json gives cross domain error i browser even if header is Access-Control-Allow-Origin:*
This example works for me you may try this. public function getOwnlist(){ $images = User::with('images.category')->find(Auth::getUser()->getAttribute('id')); return Response::json($images, 200, array('Access-Control-Allow-Origin' => '*')); } Also, I highly recommend setting those on the constructor of your Controller Base instead of setting the headers in each response. Or you can create one only to serve API and extend from it. Should be something like: protected $response; // This is a global variable on you BaseController // This goes on your BaseController constructor $this->response = Response::make(); $this->response->headers->add(array('Access-Control-Allow-Origin', '*'); I found some issues with Cross Domain AJAX while using jQuery, it only works

Categories : Ajax

Saving dynamic global data(session-token) in laravel?
You could make use of Heroku's config/environment variables for this. heroku config:set FB_ACCESS_TOKEN="abc123etcloremipsum-123456" And then in your PHP code, you would access this from $url = "https://graph.facebook.com/search?access_token=" . env('FB_ACCESS_TOKEN');

Categories : PHP

unable to generate dynamic listview through JQuery Mobile with JSON response?
Change success : function(msg) { var respPrice = ""; $.each(respPrice, function(index, value) { if(value.VarietyID == 0) { alert('No product subs list found'); } else { subsId = value.subsID; substance = value.subs; minPrice = value.MinPrice; maxPrice = value.MaxPrice; respPrice += '<li class="ui-btn ui-btn-icon-right ui-li-has-arrow ui-li ui-last-child ui-btn-up-e">' + substance + minPrice + '-' + maxPrice + '</li>'; } } $('#productList').append(respPrice).listview('refresh'); }); }, error : function(e) {

Categories : Javascript

Why Response::download() won't download anything except PDF in Laravel 4?
Try including the MIME in the return: $file = storage_path().'/file/' . $file->id . "." . $file->file->extension; return Response::download($file, 200, array('content-type' => 'image/png'));

Categories : PHP

Build Curl on vc9/vc11 with release dynamic library with dynamic ssl, ssh2 and dynamic zlib
The answer is: you can't What you should do is build curl with ssl, ssh2 and zlib internally using CFG=release-ssl-ssh2-zlib. Then use this patch to add the dlls to the link command. Note this patch is for VC10, but can easily be done on the vc9 makefile. After the builds, you will need to add libssh2.lib in to lincurl.lib, if you want to build something against it (say PHP). That can be done with this command (set the paths to the your libssh2.lib and libcurl.lib): lib.exe /OUT:libcurl_merged.lib libssh2.lib libcurl.lib copy libcurl_merged.lib libcurl.lib

Categories : Windows

.Net Web API throw exception/return response/return error response for 404/400 response?
The CreateErrorResposne extension is for creating content-negotiated responses but it also has logic of how much of this error information should be sent back to the client. The idea is to not reveal too much of information to the client which could be a security issue. For example, httpConfig.IncludeErrorDetailPolicy determines how much information is sent back to the client. The CreateResponse extension above is also for creating content-negotiated responses, but it does not have any of the additional logic that I mentioned above for CreateErrorResponse. In the third scenario, the response is not content-negotiated and you would be sending back content always in text/plain format and also it does not have additional logic as in CreateErrorResposne

Categories : Asp Net Mvc

OS X cocoa send HTTP response to PHP page, wait for PHP response to request, Continue
In fact you can use the NSMutableURLRequest, if you want to make a test to start you can do this: //test.h #import <Foundation/Foundation.h> @interface test : NSObject<NSURLConnectionDataDelegate>{ NSMutableData* _responseData; } //test.m @implementation test //Just call this method to start the request. -(void)testRequest{ //set request NSURL url = [NSURL URLWithString:@"http://ip/file.php"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:20.0]; //Start the request NSURLConnection * connection; connection = [[NSURLConnection alloc] initWithRequest: request delegate:self]; } after this you have to imp

Categories : Objective C

Image byte [] to response.outputStream in Grails leads to "Cannot forward after response has been committed"
The error you are showing has to do with at what point the code you posted gets executed. The exception says java.lang.IllegalStateException: Cannot forward after response has been committed An HttpServletResponse is typically committed, ie. the headers are sent, when you start writing to its OutputStream. At this point you cannot change the headers or status code and you cannot use a RequestDispatcher to forward() the request to another resource. Check if you are doing any of these things.

Categories : Java

How can I use Laravel 3 bunbles in laravel 4 if it doesn't have any composer support?
Why restrict yourself to Laravel bundles? Pick any composer package from packagist.org! https://packagist.org/search/?q=excel

Categories : Laravel

laravel 4 - Sanitize Input::get() (e() vs HTML::entities in laravel 4)
I have read somewhere on the web that in the blade template engine, the {{ }} automatically sanitize output. That is incorrect. You need to use three (3) curly braces to sanitize output {{{ }}} But, what if I want to echo a sanitized Input::get from the controller. You should not output from your controllers - you should do it from a view What is the best way to do it (e() which is just an htmlentities or HTML::entities or something else)? Yes - e() is the best way to do it in Laravel 4. On the backend, all that {{{ }}} is doing is actually changing to the equilivant of {{ e() }} anyway Edit: in Laravel 5 both {{ }} and {{{ }}} now sanitize output. If you need to have unsantized output in Laravel 5 - you can use {!! !!}

Categories : PHP

ServiceStack: use attribute in DTO to set response header and response body
A simpler/tidier way to achieve what you want would be to return a HttpResult and define the headers within. public object Get(Todos request) { long count; var items = _repository.GetAll(request.Query, request.Sort, request.IsDesc, request.Limit, request.Offset, out count); var response = items.Select(Mapper.Map<TodoItem, Todo>).ToList(); return new HttpResult(response, HttpStatusCode.OK) { Headers = { {"X-Total-Rows", count} } }; } This avoids polluting your response object with metadata

Categories : Angularjs

How to parse a JSON response when type is also coming in response
The usual way to deal with data items which could be any of a small known number of types is to use a tagged union. In Java, you'd write one something like this: // CREATE TABLE dataFromJson (type ENUM('INT', 'BOOLEAN', 'STRING'), // intval INT, boolval INT, stringval LONGTEXT); class DataItem { public enum Type { INT, BOOLEAN, STRING }; public Type m_type; public int m_int; public bool m_boolean; public String m_string; public PreparedStatement toInsertQuery(Connection conn) { PreparedStatement ps = conn.prepareStatement("INSERT INTO dataFromJson VALUES (?, ?, ?, ?)"); ps.setString(1, m_type.toString()); if (m_type==INT) ps.setInt(2, m_int); else ps.setObject(2, null); if (m_type==BOOLEAN) ps.setBoolean(3

Categories : Android

Laravel 4: A better way to represent this db structure/relationship within laravel
The users_clients table needs it's own ID column in order for many-to-many relationships to work. On your User Model, try public function clients() { return $this->belongsToMany('Client','user_clients','userid','clientid'); } Now you can find the clients assigned to each individual user with User::find(24)->clients. You could also do the inverse on your Client model... public function users() { return $this->belongsToMany('User','user_clients','clientid','userid'); } This would allow you to find all the users belonging to each client Client::find(42)->users; I would also like to mention that it's best practice to use snake case for your id's such as user_id or client_id. Your table names should be plural. users and clients. Your pivot table should be snake_c

Categories : Laravel

Read response from WebResponse Response Stream
you need to reduce the scope of usage for StreamWriter so it can be flushed on Dispose. let processRequest = async { while true do let! context = getContext let request = context.Request use requestReader = new StreamReader(request.InputStream) let requestString = requestReader.ReadToEnd() let response = context.Response do use streamWriter = new StreamWriter(response.OutputStream) streamWriter.WriteLine "A response!" response.Close() }

Categories : Http

HttpClient response after redirect is getting wrong response
You're getting the right response, you're just not printing it correctly. That's because you're EntityUtils.toString() on entity instead of httpEntity. Here HttpEntity httpEntity = response.getEntity(); String str = ""; if (httpEntity != null) { str = EntityUtils.toString(entity); System.out.println(str); } you pass entity which is UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); ie. the parameters. Use str = EntityUtils.toString(httpEntity); to get the HttpResponse content.

Categories : Java

Tomcat response the same every time after initital response
This turned out to be a bad case of not checking the Filters. There was a caching filter applied in the web.xml, probably the only place I didn't check. It was incorrectly using the request.getRequestURI as the key for the cache, when in reality it needed the entire request string to properly place it in the cache. Thanks

Categories : Java

Remove the response wrapper from web service response?
Found the answer... SoapDocumentMethod(ParameterStyle = SoapParameterStyle.Bare)

Categories : C#

What is the use of response.addHeader when we have response.setContentType in java
I don't write in Java, but I know there are many sharing the same feature. And IMO it's just a shortcut. BTW, there are so many headers... Not just Content-Type or something like that.

Categories : Java

How to handle the 400 response from youtube gdata "response"?
To get the response status code, I had to move the check to backend java. Javascript just couldn't do it. public static void main(String[] args) throws ParseException { String[] urls = new String[2]; urls[0] = "http://gdata.youtube.com/feeds/api/videos/OvcaXrWFM2Q"; urls[1] = "http://gdata.youtube.com/feeds/api/videos/23487978923789423789342sufyu"; HttpURLConnection con; HttpURLConnection.setFollowRedirects(false); for (String url : urls) { try { con = (HttpURLConnection) new URL(url).openConnection(); con.setRequestMethod("HEAD"); System.out.println(con.getResponseCode()); } catch (IOException e) { System.out.println(e); } } }

Categories : Ajax

Is there an upgrade guide from Laravel 3 to Laravel 4?
Official changelog should help you. Also don't forget to change your method names. All snake_case method names are converted to camelCase. Edit: folder names are almost same. application folder became app, model, view and controllers' folders' paths are still same under the app folder. Migrations are now in app/database/migrations folder. Routing has changed a bit. the :num, :all etc is dropped, now you can name them anything, and set their rules with regex. E.g: This: Route::get('my/method/(:num)', array('as' => 'name', 'uses' => 'controller@method')); became like this: Route::get('my/method/{id}', array('as' => 'name', 'uses' => 'yourController@yourMethod'))->where('id','[0-9]+'); (id is not a must, you can name it anything.) Route::get('my/method/{foo}', array(

Categories : Laravel

Laravel-Oauth2 Issue in Laravel 4
I studied the source code to the package and it appears to be an error in the Facebook Provider (actually most of the providers) In the beginning of the Facebook provider for instance it does this: <?php use OAuth2TokenToken_Access; There is actually no class in the OAuth2Token namespace. There is however one in the OAuth2 namespace. So replacing the value above with <?php use OAuth2Token_Access; Should fix your error. You should do this for all the Providers. PSR namespacing standards dictates underscores map to directories. So OAuthToken_Access class will generally be looked for in the ./OAuth/Token/Access.php file

Categories : Facebook

Spring Android Get Request implementation : Could not extract response: no suitable HttpMessageConverter found for response type and content type
Your server returns an XML content but says it returns HTML content (content type is text/html according to the error message) and thus the parsing failed. You need to make sure your server returns something like text/xml and also that you have the correct converters in you rest template object. Edit: Try to add this message converter. Put it first (before StringHttpMessageConverter and SourceHttpMessageConverter) Jaxb2RootElementHttpMessageConverter jaxbMessageConverter = new Jaxb2RootElementHttpMessageConverter(); List<MediaType> mediaTypes = new ArrayList<MediaType>(); mediaTypes.add(MediaType.TEXT_HTML); jaxbMessageConverter.setSupportedMediaTypes(mediaTypes); messageConverters .add(jaxbMessageConverter);

Categories : Android

Node.js` "http.get" doesn't return full response body to a browser but just a piece of tag. How to get full response?
Your data event is firing multiple times, but you can only "end" your output once... you should probably refactor your handler as follows... // In /myapppath http.get("http://stackoverflow.com/", function(result) { var responseParts = []; result.setEncoding('utf8'); result.on("data", function(chunk) { //add this chunk to the output to send responseParts.push(chunk); }); result.on("end", function(){ //now send your complete response res.end(responseParts.join('')); }); });

Categories : Node Js

How to do GLM where the response depends on the response of the same group?
I think you could fit a combined glm that captures the idea that "y when x2<50 is dependent on other y's of the same x3": mdl <- glm(y ~ x1 + x2 + x3:as.numeric(x2 < 50), family=binomial) For x2 >= 50, as.numeric(x2 < 50) is zero, so the model is just y ~ x1 + x2. For x2 < 50, as.numeric(x2 < 50) is one, so the model becomes y ~ x1 + x2 + x3. with this approach the coefficients for x1 and x2 are based on all the data, but the effects of x3 are based only on the data with x2 < 50.

Categories : R

Getting 411 response code while getting JSON Response
There are a few things that don't look quite right here. I would recommend trying this: httpConnection.setRequestMethod("POST"); URLEncodedPostData postData = new URLEncodedPostData("UTF-8", false); postData.append("username", user); postData.append("password", password); byte[] postDataByte = postData.getBytes(); httpConnection.setRequestProperty("Authorization", "bearer"+"ZWOu3HL4vwaOLrFAuEFqsxNQf6ka"); httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpConnection.setRequestProperty("Content-Length", String.valueOf(postDataByte.length)); OutputStream out = httpConnection.openOutputStream(); DataOutputStream dos = new DataOutputStream(out); out.write(postDataByte); out.flush(); int statusCode = httpConnection.getResponseCode();

Categories : Java

Fresh response vs Cached response in Asp.net
You should consider creating a custom OutputCacheProvider that extends the built in cache provider used in MVC. Some links that might help: MSDN Article: Building and Using Custom OutputCache Providers in ASP.NET Creating a Custom Output Cache Provider in ASP.NET 4 Custom Output Caching with MVC3 and .NET 4.0 – Done Properly! Within your provider, you can use the same functionality as the regular output cache provider. And on the Get() action, you can add content to the item returned from the cache that will indicate that it was in fact retrieved from cache (you will want to experiment with this, making sure that you are only adding this to the items that you want, and are doing it in a way that doesn't mess up the output).

Categories : Asp Net



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.