Menu
  • HOME
  • TAGS

Redirect is not working on Laravel 4

Tag: laravel,redirect,laravel-4,require

In my controller function I am using a require statement to include a file, like,

require app_path().'/plivo/plivo.php';

After this statement, when I try to redirect from this controller using the statement,

return Redirect::back()->with('success', 'Note added successfully');

It gives me an error Call to undefined method Redirect::back()

How can I redirect from this function.

This is my full code,

public function sendSMS(){
        require app_path().'/plivo/plivo.php';
        $auth_id = "XXXXXXXXXXXX";
        $auth_token = "XXXXXXXXXXXXXXXXXXXXX";
        $p = new \RestAPI($auth_id, $auth_token);

        $params = array(
                'src' => '1XX7XX0',
                'dst' => '91XXXXXXXXX7',
                'text' => 'Test SMS',
                'method' => 'POST'
            );
        $response = $p->send_message($params);
        return Redirect::back()->with('success', 'Note added successfully');
}

Best How To :

This answer assumes that plivio.php is from this git repo.

The issue is that the plivo.php library defines a Redirect class in the global namespace. Because of this, Laravel does not register the global Redirect alias to point to the Illuminate\Support\Facades\Redirect facade.

So, in your final line return Redirect::back()->with(...);, the Redirect class being used is the class defined in the plivio.php library, not Laravel's Illuminate\Support\Facades\Redirect class.

The quickest fix would be to change your line to:

return Illuminate\Support\Facades\Redirect::back()->with('success', 'Note added successfully');

Another option would be to inject Laravel's redirector into your controller, and use that instead of using the facade:

class MyController extends BaseController {

    public function __construct(\Illuminate\Routing\Redirector $redirector) {
        $this->redirector = $redirector;
    }

    public function sendSMS() {
        require app_path().'/plivo/plivo.php';
        //
        return $this->redirector->back()->with('success', 'Note added successfully');
    }
}

A third option would be to update your code to use the plivio composer package, which has a namespace. The updates have been done in the dev branch of the repo, which you can find here. If you did this, you would get rid of your require statement and use the namespaced plivio classes.

.htaccess | Too many redirects

apache,.htaccess,mod-rewrite,redirect

I'm assuming that you are trying to do two things here: Force HTTPS and www. Redirect to test.php if a certain IP is making the request The issue you were facing was due to the fact that even though the IP address was being matched, it was still being checked...

Using framework event dispatcher to raise domain event

php,events,laravel,domain-driven-design,dispatcher

Lately I favor returning events from domain methods and handling those in the application service layer. Since the application service layer is where you bring together all kinds of infrastructure further processing of the returned events, such as dispatching, can be handled in the application service layer. In this way...

Laravel - Angular Routes

php,angularjs,laravel

I had similar problem. I modified the render function in app\Exceptions\Handler.php to public function render($request, Exception $e) { if ($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) { return response()->view('index'); } return parent::render($request, $e); } and created an index.blade.php view in resources\views folder, which was like <?php include public_path().'/views/index.html'; and it contains all the angular...

Redirect specific Url variables

php,.htaccess,mod-rewrite,redirect

Try this : RewriteEngine On RewriteCond %{QUERY_STRING} ^s=([^&]+)&type=([^&]+) [NC] RewriteRule ^data.php$ /d.php?s=%1&t=%2 [NC,R,L] This will externally redirect a request for : /data.php?s=foo&type=bar to /d.php?s=foo&t=bar ...

How can I Echoing Data After Checking For Existence in PHP Laravel 5?

php,laravel,laravel-5

{{ $var or 'No Phone' }} === {{ isset($var)? $var : 'No Phone' }} Because $user->phone is defined you should use this: {{ $user->phone? $user->phone : 'No Phone' }} Or, you can go nice Laravel way and create your own directive for Blade templates and use it like this: @var($user->phone,...

Laravel 5 MethodNotAllowedHttpException

php,laravel,laravel-5,laravel-routing

Your <a> link will trigger a GET request, not a PATCH request. You can use JS to have it trigger a PATCH request, or use a <button> or <input type="submit"> to issue one.

Given an array/object of datetimes, how can I return an array/object of the times sorted by hour and times sorted by days of the week

php,arrays,sorting,datetime,laravel

You can use Laravel's collection groupBy method to group your records for your needs. $records = YourModel::all(); $byHour = $records->groupBy(function($record) { return $record->your_date_field->hour; }); $byDay = $records->groupBy(function($record) { return $record->your_date_field->dayOfWeek; }); Remember that this code to work, you have to define your date field in the $dates Model array, in...

How to register global variable for my Laravel application?

php,laravel,laravel-5

Actually, you should reserve in config/app.php file. Then, you can add In the Service Providers array : 'Menu\MenuServiceProvider', In the aliases array : 'Menu' => 'Menu\Menu', Finally, you need to run the following command; php artisan dump-autoload I assume that you already added this package in composer.json Sorry, I didn't...

Nested comments with Laravel

php,mysql,laravel,laravel-4

You want to look into polymorphic relations to solve this. You want to be able to comment on Posts and Comments. What I have done is set up a commentable trait and have the models I want to add comments to use it. This way if you ever want to...

Excluding certain pages from being redirected to https

wordpress,.htaccess,redirect,https,http-redirect

Try using THE_REQUEST instead of REQUEST_URI: <IfModule mod_rewrite.c> RewriteEngine On # Go to https if not on careers RewriteCond %{SERVER_PORT} =80 RewriteCond %{THE_REQUEST} !/careers/[\s?] [NC] RewriteRule ^(.*)$ https://www.mywebsite.com/$1 [R,L] # Go to http if you are on careers RewriteCond %{SERVER_PORT} !=80 RewriteCond %{THE_REQUEST} /careers/[\s?] [NC] RewriteRule ^(.*)$ http://www.mywebsite.com/$1 [R,L] </IfModule>...

Get Parameter from URL using PHP

php,url,redirect

You mean like this <?php session_start(); if(isset($_SESSION['postback'])) { if($_GET['postback'] == "") { header ("Location: qualify-step2.php?postback=".$_SESSION['postback']."&city=".$_SESSION['city']); } } ?>...

PDF as mail attachment - Laravel

laravel,pdf,sendmail

You can only send serializable entities to the queue. This includes Eloquent models etc. But not the PDF view instance. So you will probably need to do the following: Mail::queue('emails.factuur', array('factuur' => $factuur), function($message) { $pdf = PDF::loadView('layouts.factuur', array('factuur' => $factuur)); $message->to(Input::get('email'), Input::get('naam'))->subject('Onderwerp'); $message->attach($pdf->output()); }); ...

Laravel 4.2 Sending email error

php,email,laravel,laravel-4

Closures work just like a regular function. You need to inject your outer scope variables into function's scope. Mail::send('invoices.mail', array($pinvoices,$unpinvoices), function($message) use ($email) { $message->to($email , 'Name')->subject('your invoices '); }); ...

problems understanding workflow and set up of vagrant and laravel homestead

laravel,vagrant,virtual-machine,homestead

Are you using cygwin? You should run the commands inside the Homestead folder which is created after you do homestead init. Then you do the configuration or mapping of folders in your Homestead.yaml. it is located in you home directory. in my case in created a .homestead folder. I'm using...

Laravel relation many to many with additional pivot

php,laravel,laravel-4

As per your requirement, I blieve you have to update your relation to Polymorphic Relations. and than to access other attributes try one of them method. $user->roles()->attach(1, ['expires' => $expires]); $user->roles()->sync([1 => ['expires' => true]]); User::find(1)->roles()->save($role, ['expires' => $expires]); If you still facing some dificulties to handle that requirement let...

Update enum column in Laravel migration using PostgreSQL

postgresql,laravel,laravel-5,laravel-migrations

Laravel use constraint on character varying for enum. Assuming there is a table mytable with an enum column status, we have to drop the constraint (named tablename_columnname_check) then add it in a migration like this: DB::transaction(function () { DB::statement('ALTER TABLE mytable DROP CONSTRAINT mytable_status_check;'); DB::statement('ALTER TABLE mytable ADD CONSTRAINT mytable_status_check...

Eloquent model not updating updated_at timestamp

php,laravel,timestamp,eloquent

As mentioned in comments, if the model did not change the timestamps wont be updated. However if you need to update them, or want to check if everything is working fine use $model->touch() - more here

.htaccess allow image to display directly

php,regex,apache,.htaccess,redirect

Add conditions before your rule to skip image/css/js filesdirectories: RewriteEngine On RewriteRule !\.(?:jpe?g|gif|bmp|png|tiff|css|js)$ index.php [L,NC] ...

Join this eloquent laravel5

php,laravel

The relation is a hasMany and will therefor return a collection set, not one "echoable" thing: $mensajes = Messageuser::find(1)->conversaciones()->get(); $mensajes2 = Messageuser::find(4)->conversaciones()->get(); \dd($mensajes, $mensajes2); This will return two Collection objects dumped. Please also note that you can use: $mensajes = Messageuser::find(1)->conversaciones; To get the same return set. Now you want...

mod_rewrite - force redirecting to rewritten URL

apache,.htaccess,mod-rewrite,redirect

You need a new rule for that redirect: Options +FollowSymLinks -MultiViews RewriteEngine On RewriteBase / RewriteCond %{THE_REQUEST} /(?:index\.php)?\?search=([^\s&]+) [NC] RewriteRule ^ search/%1? [R=302,L,NE] RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^search/(.*)$ /?search=$1 [L,QSA] ...

Laravel5: Access public variable in another class

php,class,oop,laravel,laravel-5

That's simple php stuff. Set the attribute as static and access it with ::. class LanguageMiddleware { public static $languages = ['en','es','fr','de','pt','pl','zh','ja']; } @foreach (App\Http\Middleware\LanguageMiddleware::$languages as $lang) ... @endforeach You should not have that in a middleware though. You'd better add a configuration (i.e in /config/app.php) with that array, and...

Payum Laravel Package - Route not found

laravel,nvp

My suspicion is that the third parameter is expecting a route name, not a URL. Your routes.php route is not a named route. Route::get('done', ['as' => 'done', 'uses' => '[email protected]']); ...

Laravel 5 pagination with trailing slash redirect to 301

php,laravel,redirect,pagination,laravel-5

If you look in your app/public/.htaccess file you will see this line: # Redirect Trailing Slashes... RewriteRule ^(.*)/$ /$1 [L,R=301] By removing it you will disable trailing slash redirect....

Set options for ZADD command in laravel redis

php,laravel,redis,set

Until Predis' zAdd method is updated to support the changes in Redis v3.0.2, your best bet is to explore the wonderful world of RawCommand: https://github.com/nrk/predis/blob/master/src/Command/RawCommand.php It should let you construct your own commands, including the ZADD NX ... variant....

python requests with redirection

python,authentication,redirect,curl,python-requests

There is a much simpler way to perform login to this website. import requests headers = { "User-Agent": "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36", } s = requests.session() s.headers.update(headers) # There is a dedicated login page, which is the url of the Login button on...

Setting up a second Homestead Laravel app

laravel,laravel-5,homestead

The problem was in your homestead.yaml file. folders: - map: C:\Users\Lisa\Documents\Homestead\larapipeline to: /home/vagrant/Code/larapipelin - map: C:\Users\Lisa\Documents\Homestead\tinkertower to: /home/vagrant/Code/tinkertower sites: - map: homestead.app to: /home/vagrant/Code/larapipeline/public - map: tinkertower.app to: /home/vagrant/code/tinkertower/public Don't forget to edit your hosts file. Now run vagrant up --provision, or vagrant reload --provision. Edit: Fixed case sensitivity issue...

Admin login laravel 4

php,laravel

In your admin template you set the goto url as sessions.store which hits SessionsController::store in that method you have a debug function dd() which is throwing that string. It get's called because auth::attempt() returns false as by your own code: if($attempt) return Redirect::intended('/'); So the behavior is exactly doing what...

Laravel get posts with multiple tags

php,sql-server,laravel,eloquent

It would be a good idea to use whereHas() on the Post model to eager load the tags and get only the Posts which have at least one of those tags. $posts = Post::whereHas('tags', function($q) use ($tags) { $q->whereIn('id', $tags); })->get(); Here, $tags would just be an array of tag...

Laravel 5: Redirecting woes

laravel

You are trying to route something within a route definition itself. That is not how it works. There are a few ways you could do what you want to achieve. There are pros/cons to each - but they would all work. Generally the best way is to use some Auth...

How to change default Nginx setting on Homestead Laravel Virtualbox VM

laravel,nginx,vagrant,virtualbox,homestead

Easiest way to achieve this is editing scripts/serve.sh file, which contains server block template in block variable.

PHP redirect page works only in localhost

php,mysql,forms,redirect

<?php require_once('Connections/db.php'); ?> <?php if (isset($_POST['submit'])) { Change your above code to <?php require_once('Connections/db.php'); if (isset($_POST['submit'])) { and also remove the last ?> if you do not have html after that. After that, it should work. To turn on Error Reporting, place ini_set('display_errors',1); error_reporting(E_ALL); at the beginning of your php...

Laravel belongsTo throwing undefined function App/BelongsTo() exception

php,sql,laravel,eloquent,belongs-to

Well, this error occurred because I had '.' in place of '->'. I couldn't figure out why it was always throwing the exact same error regardless if I did $this.belongsTo('App\User'); or $this.hasMany('App\User'); or even $this.thecakeisalie('App\User'); until I sat staring at the text between my many models yet again. Then, lo...

Force WWW when URL contains path using .htaccess

.htaccess,session,url,redirect

It seems to look ok but one thing you should do is always put your other rules before the wordpress rules as a habit. When using wordpress it should generally be the last set of rules since it does all the routing. Now for the redirect, you should probably use...

Why mozilla changes the characters when i use the .net mvc statement redirect?

c#,asp.net-mvc-4,redirect,mozilla

%E2%80%8B is a URL-encoded, UTF-8 encoded ZERO-WIDTH SPACE character. You likely have one hiding in your application setting file for the ProActiveOffice-URL value. It was maybe pasted in that way, if you copied the URL from somewhere.

Laravel Production issue - Updating composer with Laravel 4.1.x

php,laravel,composer-php

Eventually you can install php DOM extension. Certain Linux distributions do not have this extension included in the minimum PHP package. It can usually be found in one of the "optional" php-* packages. On CentOS you should be able to just run yum install php-dom or yum install php-xml. That...

How to delete only the table relationed

sql,laravel,migration

When creating a foreign key constraint, you can also decide what should happen with the constraints. For instance, if you want to delete all articles when a category is deleted (as I guess is your question): Schema::table('articulos', function($table) { $table->foreign('categoria_id')->references('id')->on('categorias')->onDelete('cascade'); $table->foreign('creador_id')->references('id')->on('users'); }); Also see documentation. The cascade identifies to the...

What is the best practice to implement update profile picture in PHP Laravel 5?

javascript,php,jquery,laravel,laravel-5

I solved it by doing this HTML {!! Form::model($user, array('route' => array('user.update_profile_picture', $user->id ),'method' => 'PUT')) !!} <a class="pmop-edit" > <span id="file-upload" > <i class="md md-camera-alt"></i> <span class="hidden-xs">Update Profile Picture</span> </span> <div style='height: 0px;width: 0px; overflow:hidden;'> <input id="upfile" type="file" value="upload" onchange="sub(this)" /> </div> </a> {!! Form::hidden('$id', $user->id)!!} {!!...

custom orderBy() on constraining eager loads?

laravel,eager-loading

Something like this may work... the idea is to add an additional select which is 0 or 1 depending on if the date is today. Then you can order by that column first, then the actual date second. public function scopeRestaurantsWithMenusToday($query, $city_uri){ return $query->where('city_uri', '=', $city_uri)->with([ 'restaurants', 'restaurants.menusToday' => function($query)...

C# mvc4 - direct URL to controller

c#,asp.net-mvc-4,url,redirect

You might have forgotten to specify name of the controller in Html.ActionLink() parameter. Try Html.ActionLink("actionname","controllername");

Handling 500 Internal Server Error from DomDocument in Laravel 5

php,laravel,exception-handling,laravel-5

You could handle this in Laravel app/Exceptions/Hnadler.php NB: I have looked in the option of using DOMException handler which is available in PHP, however the error message you are getting in not really and exception by an I/O Warning. This what PHP native DomException looks like: /** * DOM operations...

Sync element to a child on Laravel

php,mysql,laravel,eloquent,laravel-5

As far as syncing/attaching you can use this sytanx $user->roles()->sync([1, 2, 3]); As given in Laravel Docs You can do the both checks in the condition of IF and assign in case of true, thats how your controller will look like finally. public function share(Request $request) { $userId = $request->input('user_id');...

Laravel 5: How to add Auth::user()->id through the constructor ?

authentication,laravel,constructor

You can use Auth::user() in the whole application. It doesn't matter where you are. But, in response to your question, you can use the 'Controller' class present in your controllers folder. Add a constructor there and make the reference to the user ID. <?php namespace App\Http\Controllers; use Illuminate\Foundation\Bus\DispatchesCommands; use Illuminate\Routing\Controller...

laravel file uploading using json

jquery,ajax,json,laravel,laravel-5

Use this as your code: e.preventDefault(); var mydata = new FormData($('#my_form')[0]); $.ajax({ type: 'POST', cache: false, dataType: 'JSON', url: 'tasks', data: mydata, processData: false, contentType: flase success: function(data) { console.log(data); }, }); Note that this doesn't work on some older browsers such as IE 9 or older so you might...

Laravel validator vs requests

laravel,laravel-5,laravel-validation

1. Theoretically there is no difference between Controller validation and Validation using FormRequest. Normally you should use FormRequest. This will keep your controller clean and Minimal. But some time it is sensible to use Validator within controller, e.g you know there is going to be just one field to validate,...

How to cut the content in laravel5?

php,laravel

Do you mean you want to limit the number of characters in a string? This can be done in laravel by a string helper: $value = str_limit('The PHP framework for web artisans.', 7); So in your example: <p>{{ str_limit($subasta->descripcion, 20) }}</p> ...

Javascript: OS-depending Redirects doesn't work for IOS

javascript,ios,redirect,apple

Solution: don't use the "?mt=8" parameter in the iOS-Appstore-Link and the redirect will work (and open the Appstore-App on your device)

Laravel Interfaces

php,laravel,interface,namespaces

In my recent laravel 5 project, I'm used to prepare my logics as Repository method. So here's my current directory structure. For example we have 'Car'. So first I just create directory call it libs under app directory and loaded it to composer.json "autoload": { "classmap": [ "database", "app/libs" //this...

Getting code from my forked repository

git,laravel,repository,laravel-5,composer-php

Having a look at your repository in https://github.com/Yunishawash/api-guard it looks like it doesn't have a branch called dev-fullauth. Instead there is a branch dev-bugfix. But you must not name your branch including the dev- prefix. Rename your branch at github from dev-bugfix to bugfix and then your require section would...

What does “as” keyword really mean in Laravel routing?

laravel,laravel-routing

The purpose isn't for re-direction in your routing file. Instead, with the example route you provided, Laravel will allow you to reference said route by using: $url = route('profile'); Rather then having to build the url manually in your code. So, in short: the difference is the first thing is...