lundi 31 août 2015

Laravel protect anonymous user accessing register form

in my application, i am consuming default laravel register form. i want to prevent anonymous user accessing signup form.

Current Output:- register form is not protected, so authenticated and anonymous users accessing register form

Expected output:- Authenticated user only can access this register form.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1MZd9SR
via IFTTT

Improve my parsing of JSON in PHP

Right now, I am currently parsing this JSON in a way that I feel can be improved upon. I am new at JSON, but I would expect there to be a better way of doing it than what I am currently doing.

Here is the JSON that is returned to me from Stripe's API (sensitive data removed):

Stripe\Customer JSON: { "id": "cus_6smHAG99OncrSm", "object": "customer", "created": 1440821625, "livemode": false, "description": null, "email": null, "shipping": null, "delinquent": false, "metadata": [], "subscriptions": { "object": "list", "total_count": 1, "has_more": false, "url": "\/v1\/customers\/cus_6smHAG99OncrSm\/subscriptions", "data": [ { "id": "sub_6smHbsmTA6JhrP", "plan": { "id": "yearly", "interval": "year", "name": "yearly", "created": 1439229255, "amount": 5000, "currency": "usd", "object": "plan", "livemode": false, "interval_count": 1, "trial_period_days": 7, "metadata": [], "statement_descriptor": "yearly" }, "object": "subscription", "start": 1440821627, "status": "trialing", "customer": "cus_6smHAG99OncrSm", "cancel_at_period_end": false, "current_period_start": 1440821627, "current_period_end": 1441426427, "ended_at": null, "trial_start": 1440821627, "trial_end": 1441426427, "canceled_at": null, "quantity": 1, "application_fee_percent": null, "discount": null, "tax_percent": null, "metadata": [] } ] }, "discount": null, "account_balance": 0, "currency": "usd", "sources": { "object": "list", "total_count": 1, "has_more": false, "url": "\/v1\/customers\/cus_6smHAG99OncrSm\/sources", "data": [ { "id": "card_16f0ioKTaUqqkEkT7osN0knY", "object": "card", "last4": "4242", "brand": "Visa", "funding": "credit", "exp_month": 10, "exp_year": 2017, "fingerprint": "Y1GhThZ3NCmHOdTv", "country": "US", "name": "blah@yahoo.com", "address_line1": null, "address_line2": null, "address_city": null, "address_state": null, "address_zip": null, "address_country": null, "cvc_check": null, "address_line1_check": null, "address_zip_check": null, "tokenization_method": null, "dynamic_last4": null, "metadata": [], "customer": "cus_6smHAG99OncrSm" } ] }, "default_source": "card_16f0ioKTaUqqkEkT7osN0knY" }

The main problem I am having is that I have to convert the above into a string manually and then remove the prefix (which is the "Stripe\Customer JSON:" part). Here is what I'm currently doing to parse it:

$json = strval(\Stripe\Customer::retrieve($user->stripe_id));

//Trim the prefix
$json = substr($json, 21);
$data = json_decode($json, true);
$current_period_end = $data['subscriptions']['data'][0]['current_period_end'];

The reason why I think there is a better way to do this is because I find it hard to believe that every time I receive JSON I need to convert it to a String and then find out if there is a prefix and then cut the prefix off before I can turn it into an associative array so I can use it.

Please tell me there is a better way and show me how to do it. Thank you.

On a side note, I am using Laravel, if there are any relevant features to benefit from therein I'm all ears.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1LPPa9K
via IFTTT

Laravel Database unique key between different fields

I'm building a website in laravel. The user table has two email fields, an 'email' field and a 'new_email' field. When the user wants to change emails, it gets stored in the 'new_email' first, then when the user confirms it updates the 'email' field.

All good, but I want to restrict the 'new_email' field to be unique when comparing to the 'email' field. So that no user could change his email to an existing user. I'll do the check on the php side too, but I want the database to restrict that.. so I tried the following:

    Schema::table('users', function ($table) {
        $table->string('new_email')->unique('email')->nullable();
    });

Didn't work out, I still can add an email to the 'new' field, even when it's alerady on the email..

So, how can I achieve this?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1NTsPrB
via IFTTT

Laravel cannot add foreign key constraint

When I'm trying to set a foreign key constraint in laravel 5 with migrations I receive the error:

[Illuminate\Database\QueryException] SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table rittenregistratie add co nstraint rittenregistratie_karakterrit_id_foreign foreign key (karakterrit_id) references karakterrit (id) on delete cascade) [PDOException] SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint D:\wamp\www>

But I have now idea why??? The order of migrating is right so why do I receive this error? The table rittenregistratie has a foreign key called karakterrit_id this is the primary key in the table karakterrit.

This is my migration rittenregistratie:

 public function up()
    {
        Schema::create('rittenregistratie', function (Blueprint $table) 
        {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->timestamps('datum');
            $table->integer('beginstand');
            $table->integer('eindstand');
            $table->text('van');
            $table->text('naar');
            $table->text('bezoekadres');
            $table->text('geredenroute');
            $table->integer('karakterrit_id')->default(1);
            $table->text('toelichting');
            $table->integer('kilometerszakelijk');
            $table->integer('kilomteresprive'); 

            $table->foreign('user_id')
                        ->references('id')
                        ->on('users')
                        ->onDelete('cascade');

            $table->foreign('karakterrit_id')
                        ->references('id')
                        ->on('karakterrit')
                        ->onDelete('cascade');    
        });
    }



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1KXY938
via IFTTT

Load an image from an app directory in Laravel

In my app/ directory, I create sub directory call Files/

and I stored all my blogs img in there, now I tried to display in my blade, I couldn't. Is it even possible ?


I've tried

example of my image path

/app/Files/blogs/Test/img/Screen%20Shot%202015-08-31%20at%201.35.22%20PM.png


img tag

<img src="{{app_path()}}/Files/blogs/{{$blog->name}}/img/{{$blog->img_path}}">


Block of code

<ul class="portfolioContainer grid row no_left_right isotope">

        <?php

        use App\Blog;
        $blogs = Blog::all();

        ?>


        @foreach( $blogs as $blog)

        <li class="col-xs-12 col-sm-4 col-md-4 col-lg-4 isotope-item">
            <div class="lightCon">
              <figure>
                <div class="img_hover">
                <img src="{{app_path()}}/Files/blogs/{{$blog->name}}/img/{{$blog->img_path}}">

                </div>
                <figcaption>
                  <h4><a href="#">{!! $blog->name !!}</a></h4>
                  <div class="metaInfo"> <span>By <a href="#" class="admin"></a> </span> {{ $blog->user->username }}</span></div>
                  <p>{!! $blog->description !!}</p>
                </figcaption>
              </figure>
            </div>
          </li>

        @endforeach

      </ul>

Result,

enter image description here

Console Error enter image description here

Any suggestions / hints will be much appreciated.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1UnQiRr
via IFTTT

Warning: require(/home2/sunny/public_html/apis/public/../api-project/bootstrap/autoload.php): failed to open stream:

I installed fresh larval 5.0 on my remote server.

i am getting error I installed laravel on remote server

Error -- http://ift.tt/1X6GDCQ

My server directory structure — http://ift.tt/1X6GBuQ

bootstrap/autoload.php — http://ift.tt/1Q4bxqJ

bootstrap/app.php — http://ift.tt/1X6GDCS

index.php http://ift.tt/1X6GDCW

I've tried most of the googled answers but they are not working.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1Q4bxqR
via IFTTT

The proper way to setup relationship models in Eloquent repository setup

I'm trying to figure out how to create user roles using model relationships when a user gets created from admin in my app.

I have the following tables:

users

The users table holds a list of users.

users_roles

The users_roles table is a pivot table that links roles to users.

roles

The roles table contains a list of roles.

I am trying to use a repository setup so that my controller has no mention of eloquent.

This is my controller:

class ContractorController extends Controller
{
    private $user;

    /**
     * Create a new instance.
     *
     * @return Middleware
     */
    public function __construct(UserRepoInterface $user, TimesheetRepoInterface $timesheet)
    {
        $this->middleware('actions');

        $this->user = $user;
        $this->timesheet = $timesheet;
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(CreateUserRequest $request)
    {
        // create user
        $user = $this->user->createUser($request->except('_token'));

        // user was created above so we can use $user object
        $this->user->createUserRole($user);

        return Redirect::back()->withMessage('New user created.');
    }
}

My repository:

/**
 * Create new user role.
 *
 * @param $request
 * @return mixed
 */
public function createUserRole($user)
{
    return $this->user->roles()->attach($user);
}

My User model:

/**
 * Get the roles associated with the user.
 *
 * @return Object
 */
public function roles()
{
    return $this->belongsToMany('App\Models\User\UsersRoles', 'users_roles', 'role_id', 'user_id');
}

The above code results in a record getting created in the users_roles table which is correct, however I do not know how to associate the correct role_id in the table.

Here is the data that gets inserted into users_roles:

id    user_id    role_id
1     1          0

As you can see there is no role_id because i'm not sure how I can pass this in. I know that if I was phsically creating a new role in the roles table, then I coud use this object. But the role already exists so I just need to associate this new user with a role that I specify.

Please can someone point me in te direction of how I can do this or how would I have to adjust my code?

Thanks in advance.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1X6GBer
via IFTTT

laravel validation returns error

I have a problem with laravel 5 validation on my project. As long as validation passes everything is ok. If it fails I end up with an error from the /Illuminate/Validation/Validator.php file. It says :

Call to a member function trans() on null

So i looked into the code and it sounds like the Validator class can't load the translator which is supposed to translate the error message.

Then i decided to check if the translator was accessible through the IoC container doing that somewhere in my project after the service providers have registered :

dd($this->app['translator']);

From my understanding it should have returned a Translator instance and it returned null.

I'm a little bit out of idea there so if someone has an idea but need extra informations i will be more than happy to provide.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1Q4bxaf
via IFTTT

TypeError: 'stepUp' called on an object that does not implement interface HTMLInputElement. (while using Ajax in Laravel 5)

I'm trying to create comment section and getting this error while using Ajax in Laravel 5 framework. Though I've tried different solutions, I couldn't figure the problem out. So, any opinion would be greatly appreciated.

The input fields are as follows:

<div class="panel-body">
                    {!!Form::textarea('comment', null, ['class'=>'form-control_comment', 'id'=>'comment', 'placeholder'=>'Type your comment here...'])!!}
                    <input type="hidden" name="uid" id="uid" value="{{$user->id}}">
                    <input type="hidden" name="pid" id="pid" value="{{$post->id}}">
                    <input name="_token" type="hidden" id="csrf-token" value="{{ csrf_token() }}"/>
                    <button type="button" class="btn btn-sm btn-success" id= "comment_button" style="float: right; margin: 5px;">Submit</button>
                </div>

The Ajax part:

$(document).ready(function(){
  $("#comment_button").click(function(){

            var token = $("#csrf-token").val();
            var a= $("#comment").val();
            var uid= $("#uid").val();
            var url = "<?php echo Request::root();?>";


            $.ajax({

                url: url+"post/comment_action",
                type: "POST",
                data: {"newComment":a, "uid":uid, "pid":pid, "token": token},

                success: function (newResult){


                    newResult= JSON.parse(newResult);
                    $("#all_responses").append(newResult);

                }
            });

        });
});

And the action function within the controller which is being invoked by the Ajax call:

$new_comment= Input::get('newComment');
        $uid= Input::get('uid');
        $pid= Input::get('pid');
        $com= new Comment;
        $com->content= $new_comment;
        $com->userId= $uid;
        $com->postId= $pid;
        $com->save();

        $data= array();

        $all_comments= Comment::where('postId', $pid)->first();
        $u= User::where('id', $uid);

        foreach($all_comments as $coms)
        {

            $data= "<div class=\"response_top_div\"><a href=\"#\">".$u->name."</a> &nbsp; &nbsp; &bull; &nbsp; &nbsp; <small>" . $coms->created_at->diffForHumans() . "</small></div><div class=\"response_div\">" . $coms->content . "</div>";
        }

        $data= json_encode($data);
        echo $data;



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1Q45535
via IFTTT

Query builder in a queued command in Laravel 5

I'm using Laravel 5.0 and I've created a queued command with the Artisan CLI:

php artisan make:command SendEmail --queued

I need to use the DB::table() query builder method into this command, but I'm not able to make it work.

This is an excerpt of my code:

<?php namespace App\Commands;

use App\Commands\Command;
use DB;

use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldBeQueued;

class SendEmail extends Command implements SelfHandling, ShouldBeQueued {

use InteractsWithQueue, SerializesModels;

protected $message;

public function __construct($message)
{
    $this->message = $message;
}

public function handle()
{
    $data = DB::table('structures')->where('id', '=', '1')->first();
    // $data is always empty even if database connection works outside the command!!! <-------------------
    // no error exception is thrown
}

}

What am I doing wrong?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1KzoZmi
via IFTTT

Laravel error with foreign key

When I'm trying to set a relation between two tables I receive the error:

D:\wamp\www>php artisan migrate Migration table created successfully.

[Illuminate\Database\QueryException] SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table rittenregistratie add co nstraint rittenregistratie_karakterritid_foreign foreign key (karakterritid) references karakterrit (id) on d elete cascade)

[PDOException] SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

D:\wamp\www>

This is my migration rittenregistratie (it's dutch) :

    <?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateRittenregistratieTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('rittenregistratie', function (Blueprint $table) 
        {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->timestamps('datum');
            $table->integer('beginstand');
            $table->integer('eindstand');
            $table->text('van');
            $table->text('naar');
            $table->text('bezoekadres');
            $table->text('geredenroute');
            $table->integer('karakterritid')->default(1);
            $table->text('toelichting');
            $table->integer('kilometerszakelijk');
            $table->integer('kilomteresprive');

            $table->foreign('user_id')
                        ->references('id')
                        ->on('users')
                        ->onDelete('cascade');

            $table->foreign('karakterritid')
                        ->references('id')
                        ->on('karakterrit')
                        ->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('rittenregistratie');
    }
}

This is where I want to relate to:

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateKarakterritTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('karakterrit',function(Blueprint $table)
        {
            $table->increments('id');
            $table->text('rit');          
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('karakterrit');
    }
}

What is am I doing wrong?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1KyKYtI
via IFTTT

Laravel: calling controller method from another location

In my Laravel app I have the following controller that takes the instance of Elastic search as a first parameter and then another variable:

use Elasticsearch\Client;
use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

class AngularController extends Controller {
    public function selectRandom(Client $es, $numRows) {
        # ...search params here
        $results = $es->search($searchParams);
        return $results;
    }
}

I need to call the method of the controller above from another controller, I do it like this:

class HomeCtrl extends Controller {

    public function index() {

        $featured = new AngularController();

        return $featured->selectRandom(12);
    }

}

I get the following error

Argument 1 passed to App\Http\Controllers\AngularController::selectRandom() must be an instance of Elasticsearch\Client, integer given

I'm not well versed in OOP. Do I call it incorrectly? Because I though the method I call would take instance that it injected in controller, not from where I call it.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1NRUMzQ
via IFTTT

Laravel routes issue with Lowercase

I am trying to setup this route

http://ift.tt/1N3VgUv

My code in Routes file is

Route::resource('/doctor/updateschedule', 'Doctor\DoctorController@doctorSchedule');

But this does not work, It only works if I Use an Uppercase

http://ift.tt/1KWJpBr

And in Routes,

Route::resource('/Doctor/updateschedule', 'Doctor\DoctorController@doctorSchedule');

There is nothing in the Controller's action, just an echo "Hello". it only works with an uppercase /Doctor/updateschedule

Can anyone tell me why this is happening and how can i make it work for lowercases?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1N3VhYs
via IFTTT

How to fetch id of softdeleted data in laravel 4.2

 Model->

 use Illuminate\Database\Eloquent\SoftDeletingTrait;

 class Tasktime extends Eloquent

 {
public $table='tasktime';
use SoftDeletingTrait;

protected $softDelete = true;

protected $dates = ['deleted_at'];     }

Controller

public function releaseleader($id)
{

    $leader=Tasktime::find($id);
    $leader->delete();


        return Redirect::to('managertask/'.$id);
}

For example After softdelete it is not redirected to page with id such as managertask/17

But Before softdlete it is redirecting to page having id 17

Please help me



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1N3VgUr
via IFTTT

Laravel Eloquent inserting relationship models

I'm trying to insert data into a pivot table using an Eloquent relationship model. I will try to explain below my current setup in the simplest terms.

I have 3 tables:

Users - this table is used to store users.

id    name    
1     John Smith
2     Fred Bloggs

UsersRoles - this table is a pivot table which is used to store the role a user has. A user may have multiple roles. The only role that we are interested in in this circumstance is the supervisor (which has a role_id of 2). The below example means that John Smith is a member of the supervisor role.

id    role_id    user_id
1     2          1
1     1          2

UserSupervisors - this table is the pivot table used to store supervisors that have been assigned to users. The below table shows that Fred Bloggs has John Smith as a supervisor.

id    user_id    supervisor_id
1     2          1

I have the following controller method which creates new users:

/**
 * Store a newly created resource in storage.
 *
 * @param  Request  $request
 * @return Response
 */
public function store(CreateUserRequest $request)
{
    // create user
    $user = $this->user->createUser($request->except('_token'));

    // create roles
    $this->user->createUserRoles(['user_id' => $user->id, 'role_id' => $this->user->findRoleByName('Contractor')->id]);

    // assign supervisors
    $this->user->assignContractorSupervisors($request->get('supervisors'));

    // send activation
    Event::fire(new UserCreated($user));

    return Redirect::back()->withMessage('New user created.');
}

The issue I am having is with assignContractorSupervisors(). This method calls a method within my repository which is below:

/**
 * Contractor supervisors.
 *
 * @return Object
 */
public function assignContractorSupervisors($request)
{
    return $this->user->contractorSupervisors()->insert($request);
}

The above method calls the belongsToMany method in my model:

/**
 * Supervisor belongs to many contractors.
 *
 * @return Object
 */
public function contractorSupervisors()
{
    return $this->belongsToMany('App\Models\User\ContractorSupervisors', 'contractor_supervisors', 'user_id', 'supervisor_id');
}

My problem is that the data gets inserted into the contractor_supervisors table but without a user_id, see below:

id    user_id    supervisor_id
1     0          1

How can I link up the user_id that was created by $user = $this->user->createUser($request->except('_token')); and insert this id into my pivot table?

Thanks in advance.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1KWESyT
via IFTTT

Laravel routes does not exist

I'm working on a laravel 5 project but now I receive the error:

ReflectionException in Container.php line 736: Class App\Http\Controllers\routes does not exist

But that's strange because when I do a new installation of laravel that App\Http\Controllers\routes doesn't even excist? The routes file is normally in App\Http. What could be wrong, here is the full error:

> ReflectionException in Container.php line 736:
Class App\Http\Controllers\routes does not exist
in Container.php line 736
at ReflectionClass->__construct('App\Http\Controllers\routes') in Container.php line 736
at Container->build('App\Http\Controllers\routes', array()) in Container.php line 626
at Container->make('App\Http\Controllers\routes', array()) in Application.php line 674
at Application->make('App\Http\Controllers\routes') in ControllerDispatcher.php line 85
at ControllerDispatcher->makeController('App\Http\Controllers\routes') in ControllerDispatcher.php line 57
at ControllerDispatcher->dispatch(object(Route), object(Request), 'App\Http\Controllers\routes', 'index') in Route.php line 201
at Route->runWithCustomDispatcher(object(Request)) in Route.php line 134
at Route->run(object(Request)) in Router.php line 704
at Router->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 139
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Router.php line 706
at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 671
at Router->dispatchToRoute(object(Request)) in Router.php line 631
at Router->dispatch(object(Request)) in Kernel.php line 236
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 139
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in VerifyCsrfToken.php line 50
at VerifyCsrfToken->handle(object(Request), object(Closure))
at call_user_func_array(array(object(VerifyCsrfToken), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in ShareErrorsFromSession.php line 54
at ShareErrorsFromSession->handle(object(Request), object(Closure))
at call_user_func_array(array(object(ShareErrorsFromSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in StartSession.php line 62
at StartSession->handle(object(Request), object(Closure))
at call_user_func_array(array(object(StartSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in AddQueuedCookiesToResponse.php line 37
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure))
at call_user_func_array(array(object(AddQueuedCookiesToResponse), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in EncryptCookies.php line 59
at EncryptCookies->handle(object(Request), object(Closure))
at call_user_func_array(array(object(EncryptCookies), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in CheckForMaintenanceMode.php line 42
at CheckForMaintenanceMode->handle(object(Request), object(Closure))
at call_user_func_array(array(object(CheckForMaintenanceMode), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Kernel.php line 122
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 87
at Kernel->handle(object(Request)) in index.php line 54



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1LEYNFx
via IFTTT

Laravel Migration Table Naming

I just used Artisan CLI to make a migration for a model called story:

php artisan make:model Story

And it created a migration file that creates a table called stories and not storys. Even though it is grammatically correct, it makes me wonder what other non-conventional corrections it can make. In other words, what are rules that CLI follows to create a migration file? Also, do these "correct" names apply to column names or not? Will the migration table for a polymorphic tags table be taggable_id or tagable_id? Bear in mind that Eloquent doesn't expect a taggable_id by default.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1N3KGga
via IFTTT

dimanche 30 août 2015

Trying to get property of non-object in laravel

i have following code

in controller

public function ViewPost($id)
    {
         $viewpost= Post::find($id);
          return view('Guest.viewpost', ['viewpost'=>$viewpost]);
    }

in view

@foreach($viewpost as $val)

    <br>
    Post title=
    <a href="viewpost/{{$val->id}}" >{{$val->post_title}}</a>
  <br>
    Post content={{$val->post_content}}
    <br>  <br>
    Featured Image=<img src="{{$val->featured_image}}" height="150" width="150">
  @endforeach

but above code thow an error Trying to get property of non-object.so i tried following way

$val['post_title'];

the above code wont throw an error nor displaying output.

if i print in controller it display output but same in view if i print it give error

print_r($viewpost);

I am using laravel 5.1.Can any one tell us what i am doing wrong ?.Thank you.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1fQuEaG
via IFTTT

How to get Model Object using its name from a variable in Laravel 5?

I am trying to get information from a model using its name which is sent as parameter from blade using ajax call.

$.get("{{ url('auditInformation')}}", {modelName: modelName,versions:versions,currentData:currentData[index]});

Now i need to retrieve information using modelName from a model.

So when i tried this:

$auditInfo=Input::all();
    $modelName=$auditInfo['modelName'];
    $values=$modelName::find(1);

I got this response Class 'Designation' not found

But if i use

$modelName=new Designation();
    $values=$modelName::find(1);

then it shows data exactly what i want.

So i understand that this is all about model ( class ) object.

Is there any way to assign object to $modelName using $auditInfo['modelName'] .

Thanks



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1EuP5pB
via IFTTT

Where can I find steps to install virtualbox on Windows 7 in preparation for installing homestead?

I am going in circles trying to figure out how to get Laravel Homestead on my Windows 7 machine. Every discussion starts with the instructions to first setup Vagrant and VirtualBox. I downloaded VirtualBox and installed it. I downloaded Vagrant. As far as I can tell the next step is to open a cmd window and run the following commands:

$ vagrant init hashicorp/precise32
$ vagrant up

But the vagrant up command starts downloading virtualbox all over again (and it looks like a very long download) What do I need to do to VirtualBox so that it is ready for Vagrant? and then ready for Homestead?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1Ixx9Wi
via IFTTT

How to secure app.php encryption key? (Laravel 5)

According to this, Laravel supports encryption and decryption of data. It works well and is easy to set up, but my question is how secure is it really?

What if the encrypted fields in the database are compromised and then the app.php file is also compromised? Then they will have access to the encryption key.

Is there a way we can programmatically secure the encryption key from hackers?

This answer is certainly helpful, but I'm wondering if there is a specific method for Laravel apps. Appreciated!



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1UgsVOU
via IFTTT

How to make Compact code Laravel 5 Eloquent Relationships

I have this not simple code on my Controller:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use App\UserDetail;
use App\UserSex;
use App\Province;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class UserController extends Controller {

...

public function show($id) {
        //
        $User = User::find($id);
        $UserDetail = User::find($id)->UserDetail;
        $UserSex = User::find($id)->UserSex;
        $Province = User::find($id)->Province;
        return view('users.show', compact('UserDetail', 'User', 'UserSex', 'Province'));
    }

...

This code on one of my Model:

namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract {

...

protected $hidden = ['password', 'remember_token'];
    public $timestamps = false;

    public function UserDetail() {
        return $this->hasOne('App\UserDetail', 'userDetail_id');
    }

    public function UserSex() {
        return $this->hasOne('App\UserSex', 'sex_id');
    }

    public function Province() {
        return $this->hasOne('App\Province', 'province_id');
    }

...

And this code on view:

<div class="form-group">
        <label for="isbn" class="col-sm-2 control-label">User Name</label>
        <div class="col-sm-10">
            <input type="text" class="form-control" id="isbn" placeholder="{!! $User->username !!}" readonly>
        </div>
    </div>
    <div class="form-group">
        <label for="title" class="col-sm-2 control-label">Full Name</label>
        <div class="col-sm-10">
            <input type="text" class="form-control" id="firstName" placeholder="{!! $UserDetail->firstName !!} {!! $UserDetail->lastName !!}" readonly>
        </div>
    </div>
    <div class="form-group">
        <label for="publisher" class="col-sm-2 control-label">Sex</label>
        <div class="col-sm-10">
            <input type="text" class="form-control" id="sex" placeholder="{!! $UserSex->gender !!}" readonly>
        </div>
    </div>

As you see in my controller, I call every function in model (return view('users.show', compact('UserDetail', 'User', 'UserSex', 'Province'));) to show the data between table in Eloquent Relationships.

I have no error doing code like this and this run well.

My question is, am I doing it right (base on Laravel 5)?

Because I think this method is not simple, not compact if I make a lot of table later. I still have not explored all the laravel features. Maybe some of you can help me make it right.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1EusY2B
via IFTTT

Laravel custom error message

I am developing a web application using laravel5. I want to remove the default error message and put my custom error message.How do i do that?

Thanks in advance



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1NQNQTG
via IFTTT

Laravel - How implement remember me using session

My application is built on OctoberCMS (that implements Laravel at all) and i'm not able to use Auth facade. So, i'm using Session (database driver) to manage user authentication.

Now, i want to implement "remember me" funcionality.

How i can do that?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1Q1DhfH
via IFTTT

How to make user, role and user_roles relationship in laravel 5?

I have three tables :

User ->
 id : 
 name : 

Roles ->
 id :
 role_name :
 access :

user_roles->
 id :
 user_id : ->references('id')->on('users');
role_id : ->references('id')->on('roles');

I am trying to access user_roles details from user.

My user model has :

public function role(){
        return $this->belongsTo('App\Role');
    }

My role model has :

public function user(){
      return $this->belongsToMany('App\User');
  }

When I try to do following :

$user = User::find(1);

        $details = [
            'name' => $user->first_name,
            'role' => $user->role->name

        ];

I get error :

Trying to get property of non-object

How to do that?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1X21KGx
via IFTTT

How upload laravel 5.1 project on server step by step

i'm uploud laravel folder on root server and public file on public_html but not work! please descripton how upload laravel 5.1 project on server tnx



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1X21My3
via IFTTT

Laravel add new array key to eloquent insert

I am trying to add a user_id array key when doing an eloquent insert. I have the following setup:

View

{!! Form::label('supervisors', 'Assign Supervisor(s)') !!}
{!! Form::select('supervisors[][supervisor_id]', $supervisors, null, ['class' => 'chosen-select', 'multiple']) !!}

Currently the request $request->get('supervisors') outputs this:

array:1 [▼
  0 => array:1 [▼
    "supervisor_id" => "1"
  ]
]

However, I would like it to output this:

array:1 [▼
  0 => array:1 [▼
    "supervisor_id" => "1",
    "user_id" => "12"
  ]
]

How can I achieve this dynamically?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1KvpHRD
via IFTTT

Changes in database configuration do not take effect

In laravel 5, I created Middleware that changes the database credentials:

config([ 'database.connections.mysql.database' => 'someDB', 'database.connections.mysql.username' => 'someUser', 'database.connections.mysql.password' => 'somePass' ]);

Using a route that makes use of the middleware, I tried to output the current database within the controller:

exit(config('database.connections.mysql.database'));

The information is correctly set to 'someDB'. When i use eloquent in the same function it tries to contact the 'old' database and not the 'someDB' settings I've set in the middleware.

Any thoughts about this?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1X1QVnN
via IFTTT

assign value to variable when clicke on button inside foreach loop in php blade template

I have been using angular js to develope web applications and i am quite fan of it. Just starting my hands on laravel 5 to learn something new. I am trying to find angular's ng-click replacement in laravel for blelow situation.

I am using simple html (no php form tags) to insert some data and display it in php blade templete using blade's @foreach control sturcture like below

<table class="table table-bordered table-striped table-hover">

          <tr>
            <th>S.No</th>
            <th>Name of value</th>
                            <th></th>
          </tr>     
          @foreach( $valuess as $index=>$value)
          <tr>
            <td>{{$index +1}}</td>
            <td>{{$value->value_name}}</td>

                            <td><button class="btn btn-success btn-sm" data-toggle="modal" data-target="#editValueModal" onclick="<?php $selectedValue = $value ?>">Edit</button></td>
          </tr> 
          @endforeach


         </table>

data is being displayed properly. As you can see on click "edit" button i open a popup . Now here the problem comes. I am trying to display the value_name in the popup whose edit button is being clicked. i tried to use html's onclick function to set a variable for the correspoiding $value object but it is always setting the last $value of loop in the variable $selectedValue.

Can some please tell me the way i can do it.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1UeOHCx
via IFTTT

Site template without using Blade

How to structure view hierarchy without using blade? What are the pure php counterparts of blade directives (i,e @section, @extend , etc)?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1EqIGvl
via IFTTT

what is the benefit using route:chace in laravel 5

I'm new to Laravel, and also new to PHP. and I have the following command that laravel 5 can chace the route :

$ php artisan route:cache
  Route cache cleared!
  Routes cached successfully!

My Questions are :

  1. What is the Benefit using route:chace in Laravel 5?
  2. do I have to use it in production mode?
  3. And what is the different between using route:chace and not using it? is it faster?

Thank you.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1hMuVxp
via IFTTT

Laravel export excel

When I'm follow this instruction:

http://ift.tt/1NPnzVJ

For exporting an excel document. It says that I've to do this for laravel 5:

After updating composer, add the ServiceProvider to the providers array in app/config/app.php

'Maatwebsite\Excel\ExcelServiceProvider',

But all my providers in the providers array have something like this:

Illuminate\Auth\AuthServiceProvider::class,

So should I put this here?

Illuminate\Maatwebsite\Excel\ExcelServiceProvider:class,

that doesn't work?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1fOIiey
via IFTTT

select2.js and select with content of two columns visible - laravel

I have a form and a select field in it. I also use select2.js to style the field

The select is populated by this collection

$dis = array(null => 'Please select district name...') + District::orderBy('id','asc')->lists('name_region', 'id')->all();

The code in my view is

{!! Form::select('electoraldistrict_id', $dis, Input::old('electoraldistrict_id')) !!}

Problem: Now in the select field I only see the name of the district.

How I can make the form to display BOTH id and name - so that in the field I would see sht like this:

1 - first district
2 - second district

instead of

first district
second district



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1NGJkrR
via IFTTT

samedi 29 août 2015

How to use hasManyThrough relationship in Laravel?

I have the following tables in my schema:

orders |order_items | users | items | providers

orders has a user_id.

order_items has order_id and item_id.

items has provider_id.

Now, how do I fetch all the orders (eager loaded) with order_items, items, students and providers.

I've tried using the hasManyThrough method of Laravel Eloquent but it didn't work. Like this:

//Order.php Eloquent Model
public function items()
    {
        return $this->hasManyThrough('App\Item','App\OrderItem','item_id','id');
    }

I added the hasManyThrough method to other models as necessary.

Can someone help me through? Just give me a hint and I'll pick it up.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1JtzdTd
via IFTTT

TokenMismatchException in VerifyCsrfToken

I am creating an angular app which hits a Laravel 5 api. I am working on user login/auth right now and am getting a TokenMismatchException in VerifyCsrfToken when I try to post via DHC, and a cors error when I try to log in through my application even though I have specified posts in my cors (See below).

You'll notice my AuthController below redirects because I am not using blade for templating, rather just using laravel for API endpoints.

a) I am not sure what VerifyCsrfToken is

b) Why my cors is acting up

Angular App:

Login Controller:

        Auth.login({
            username: $scope.user.username,
            password: $scope.user.password
        }).success(...

Auth Service:

      return {
        login: function(params) {
            return $http({
                method: 'POST',
                url: 'http://ift.tt/1VmuiJ8',
                data: params,
                cache: true
            });
        },

Laravel 5 API:

routes:

Route::group(['middleware' => 'cors'], function(\Illuminate\Routing\Router $router) {
   $router->get('/api/questions', 'ApiController@getQuestions');

   //Auth
   $router->controllers([
       'auth' => 'Auth\AuthController',
       'password' => 'Auth\PasswordController'
   ]);

Auth Controller:

class AuthController extends Controller {

use AuthenticatesAndRegistersUsers, ThrottlesLogins;
...

AuthenticatesAndRegistersUsers trait:

namespace Illuminate\Foundation\Auth;

trait AuthenticatesAndRegistersUsers
{
    use AuthenticatesUsers, RegistersUsers {
        AuthenticatesUsers::redirectPath insteadof RegistersUsers;
    }
}

AuthenticatesUsers.php

public function postLogin(Request $request)
{
    die('post login');  //not reaching this
    $this->validate($request, [
        $this->loginUsername() => 'required', 'password' => 'required',
    ]);

When I post to dde.localhost/auth/login in DHC, I get

TokenMismatchException in VerifyCsrfToken

When I login (post) from my Angular application, I get a cors issue:

enter image description here

This shouldn't happen because I am using cors middleware for my routing:

Route::group(['middleware' => 'cors'], function(...

Which allows POSTS from any application (here is my cors.php middleware):

return [
    'supportsCredentials' => false,
    'allowedOrigins' => ['*'],
    'allowedHeaders' => ['*'],
    'allowedMethods' => ['GET', 'POST', 'PUT',  'DELETE'],
    'exposedHeaders' => [],
    'maxAge' => 0,
    'hosts' => [],
];



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1VmuiZm
via IFTTT

Laravel route list returns error

When i try to show list of available routes artisan returns the following error:

   $ php artisan route:list

      [ReflectionException]
      Class API does not exist

It worked a while ago but now i can't get it to work.

Laravel version is:

$ php artisan -V
Laravel Framework version 5.1.10 (LTS)

Is it possible to debug somehow this error?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1hnXUXn
via IFTTT

Bidimensional array of input values

I know that it's possible to store input values in a array when they have the same name like this:

<label>Quantity</label>
<input type="number" name="quantities[]">

<label>Quantity</label>
<input type="number" name="quantities[]">

That would output:

[
    0 => "3"
    1 => "65"
]

But i have to store the item selected with the quantity specified like this:

[
    0 => [
             0 => "38" //item
             1 => "3"  //quantity
         ]
    1 => [
             0 => "799"
             1 => "65"
         ]
] 

How could i do that? Or should i make two different arrays then?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1KTOzhM
via IFTTT

Cannot login with username on Sentinel (Laravel5)

I am trying out the sample Sentinel methods. I just want to register a user and authenticate him using his username.

I modified the user table by replacing the email attribute with username and did the migration. Here is my users table.

Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('username');
        $table->string('password');
        $table->text('permissions')->nullable();
        $table->timestamp('last_login')->nullable();
        $table->timestamps();

        $table->engine = 'InnoDB';
        $table->unique('username');
    });

When I try to call the below method to register a sample user, I am getting an error.

Code:

$credentials = [
   'username' => 'testuser123',
   'password' => '123'
];

$activation =  Sentinel::registerAndActivate($credentials);

Error:

InvalidArgumentException in IlluminateUserRepository.php line 271:
No [login] credential was passed.
in IlluminateUserRepository.php line 271
at IlluminateUserRepository->validateUser(array('username' => 'testuser123', 'password' => '123')) in IlluminateUserRepository.php line 154
at IlluminateUserRepository->validForCreation(array('username' => 'testuser123', 'password' => '123')) in Sentinel.php line 164
at Sentinel->register(array('username' => 'testuser123', 'password' => '123'), true) in Sentinel.php line 191
at Sentinel->registerAndActivate(array('username' => 'testuser123', 'password' => '123')) in Sentinel.php line 97
at Sentinel::__callStatic('registerAndActivate', array(array('username' => 'testuser123', 'password' => '123'))) in AuthenticationController.php line 196
at Sentinel::registerAndActivate(array('username' => 'testuser123', 'password' => '123')) in AuthenticationController.php line 196
at AuthenticationController->testFunction()
at call_user_func_array(array(object(AuthenticationController), 'testFunction'), array()) in Controller.php line 246
at Controller->callAction('testFunction', array()) in ControllerDispatcher.php line 162
at ControllerDispatcher->call(object(AuthenticationController), object(Route), 'testFunction') in ControllerDispatcher.php line 107
at ControllerDispatcher->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 141
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 101
at Pipeline->then(object(Closure)) in ControllerDispatcher.php line 108
at ControllerDispatcher->callWithinStack(object(AuthenticationController), object(Route), object(Request), 'testFunction') in ControllerDispatcher.php line 67
at ControllerDispatcher->dispatch(object(Route), object(Request), 'App\Http\Controllers\AuthenticationController', 'testFunction') in Route.php line 204
at Route->runWithCustomDispatcher(object(Request)) in Route.php line 134
at Route->run(object(Request)) in Router.php line 701
at Router->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 141
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 101
at Pipeline->then(object(Closure)) in Router.php line 703
at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 670
at Router->dispatchToRoute(object(Request)) in Router.php line 628
at Router->dispatch(object(Request)) in Kernel.php line 214
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 141
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in ShareErrorsFromSession.php line 55
at ShareErrorsFromSession->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in StartSession.php line 61
at StartSession->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in AddQueuedCookiesToResponse.php line 36
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in EncryptCookies.php line 40
at EncryptCookies->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in CheckForMaintenanceMode.php line 42
at CheckForMaintenanceMode->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 101
at Pipeline->then(object(Closure)) in Kernel.php line 115
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 84
at Kernel->handle(object(Request)) in index.php line 53
at require_once('/home/pranavaghanan/Documents/GitHub Projects/To Integrate For Release 1/SEP/public/index.php') in server.php line 21

Is there any way to correct the problem? Thanks.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1JDFSaj
via IFTTT

ho to select last 30 day data with join table user and employees table in laravel 5.0

recent_employees =DB::table('users.created_at') ->join('employees', 'users.id', '=', 'employees.user_id')

        ->select('users.id', 'name','created_at')
        ->where DATE_SUB(CURDATE(),INTERVAL 30 DAY) <= 'created_at';
        ->get();



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1hL8Mzm
via IFTTT

What's happening to my routes in Laravel 5?

I've done a few blade directives to have in my masterpage, but the @abouturl() directive seems weird. When I go to http://localhost:8080/laravel_blog/w/about/# it just redirects to http://localhost:8080/about/.

But when I open a new browser (IE) and go directly to http://localhost:8080/laravel_blog/w/about/ the route works, but when I click the about link it goes straight to the server root url + '/about' again, and then I can't access the about page again in the new browser. Seems weird?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1JDk4LR
via IFTTT

Laravel POST request working in Local and throwing 500 on the remote server(digital ocean)

I am creating API using Laravel 5! I tested the services(Get & POST) locally, but when deployed on the remote server(Droplet on Digital Ocean) the POST requests doesn't work.

Is there any configuration changes i need to make in the project to allow POST/PUT calls?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1UcTJ2t
via IFTTT

Laravel 5 - Class not found

My problem is, when i try to call a class from my controller, Laravel returns that did not found the class

In my controller:

$get_connections = Mail_server_connection::get_connection();
print_r($get_connections);

Error:

Symfony \ Component \ Debug \ Exception \ FatalErrorException (E_UNKNOWN)    
Class 'App\models\Mail_server_connection' not found 

It is the first time that i occur this error, i want also to notice that i have modified the auth.php and the User.php model in order to change Laravel's default User.php to a custom one with a custom table in MySql

Any suggestion will be helpful.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1JD42Sg
via IFTTT

laravel 5 show name instead of showing id

I have 2 table department and student in laravel 5 framework.i want to do the following program:when i input one department name like CSE OR EEE, then the student form automatic got the department name which student form contain name, gpa, roll, department name(this department field automatic selected when i put department name in the first department table).then after fill up the student form then all form data show in the view page but in the view page the department section show department name in department field with other name, gpa, roll field.please anybody give a solution as soon as possible.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1KsWNBr
via IFTTT

Laravel 5 query `LIKE` issue

I have a special_number table with a prefix column. The column contains 022,021 etc data. I have a number 0216627363021. How I match the column using LIKE keyword to get the row.

$rate = Special::where('user_id',$user_id)
            ->where(DB::raw("prefix LIKE $number"))
            ->orWhere(DB::raw("prefix LIKE SUBSTR($number,1,-1)"))
            ->orWhere(DB::raw("prefix LIKE SUBSTR($number,1,-2)"))
            ->orWhere(DB::raw("prefix LIKE SUBSTR($number,1,-3)"))
            ->orWhere(DB::raw("prefix LIKE SUBSTR($number,1,-4)"))
            ->orWhere(DB::raw("prefix LIKE SUBSTR($number,1,-5)"))
            ->orWhere(DB::raw("prefix LIKE SUBSTR($number,1,-6)"))
            ->orWhere(DB::raw("prefix LIKE SUBSTR($number,1,-7)"))
            ->orWhere(DB::raw("prefix LIKE SUBSTR($number,1,-8)"))
            ->orWhere(DB::raw("prefix LIKE SUBSTR($number,1,-9)"))
            ->orWhere(DB::raw("prefix LIKE SUBSTR($number,1,-10)"))
            ->first();

but it return NULL. Where is the problem? Thank you.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1F5XR8a
via IFTTT

create table in html with Variable rows and its cells get data from user in view of laravel-5

<table class="table table-bordered table-condensed" id="stepTable">
  <thead>
    <tr>
      <td>step</td>
      <td>payment</td>
      <td>date</td>
    </tr>
  </thead>
  <tbody>
    <tr>
       <td>1</td>
       <td><input type="number" class="form-control" name="inPayment1" /></td>
       <td><input type="date" class="form-control" name="inDate1" /></td>
    </tr>
    <tr>
       <td>2</td>
       <td><input type="number" class="form-control" name="inPayment2" /></td>
       <td><input type="date" class="form-control" name="inDate2" /></td>
    </tr>
    <tr>
       <td>3</td>
       <td><input type="number" class="form-control" name="inPayment3" /></td>
       <td><input type="date" class="form-control" name="inDate3" /></td>
    </tr>
  </tbody>
</table>

I want a table like this with specified head row . also i want have a button that inserts new row the first column is automatically numbered and tow others get data from user. I write code handy what is the automatically way?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1WZ0UKE
via IFTTT

Difference Request vs Input in Laravel 5.1

What's the difference between Requests and Inputs in Laravel 5.1? And what is the advantage or disadvantage in getting the data's from the client side?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1fMu4uE
via IFTTT

Switching from Illuminate\Htm to Collective\Html, Class 'Illuminate\Html\HtmlServiceProvider' not found

I updated composer.json to remove illuminate\html and add:

"require": {
    "laravelcollective/html": "5.1.*"

I removed the providers/aliases from app.php for Illuminate\Html and added the replacements:

    Collective\Html\HtmlServiceProvider::class,

...

    'Form'      => Collective\Html\FormFacade::class,
    'Html'      => Collective\Html\HtmlFacade::class,

However when running composer update I receive the output:

$ composer update
Loading composer repositories with package information
Updating dependencies (including require-dev)
- Removing illuminate/html (v5.0.0)

- Installing laravelcollective/html (v5.1.4)
  Downloading: 100%  

Writing lock file
Generating autoload files
> php artisan clear-compiled
PHP Fatal error:  Class 'Illuminate\Html\HtmlServiceProvider' not found in vendor/laravel/framework/src/Illuminate/Foundation/Application.php on line 648

[Symfony\Component\Debug\Exception\FatalErrorException]  
Class 'Illuminate\Html\HtmlServiceProvider' not found                                                     

Script php artisan clear-compiled handling the post-update-cmd event returned with an error

[RuntimeException]                                                                   
Error Output: PHP Fatal error:  Class 'Illuminate\Html\HtmlServiceProvider' not found in vendor/laravel/framework/src/Illuminate/Foundation/Application.php on line 648 

I tried updating composer.json scripts as suggested here: http://ift.tt/1EqU6zG

But I'm still receiving the error. Any help is greatly appreciated :)



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1EqU6zI
via IFTTT

Laravel 5.1 delete a specific table using rollback

I am using laravel 5.1 I have 6 table in my project, suppose table_1, table_2, table_3, table_4, table_5,table_6. In this time I need not table_3.My all table are created using migration and all are filled with data, There are no foreign key.Now I want to delete table_3 using rollback, Is it possible? If how?

Thank you in advance



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1NFbiEf
via IFTTT

vendredi 28 août 2015

Redirect to route with parameters in Laravel 5

I know how to send parameters to a route redirect, what i don't know is how to get that parameters in the route controller function...

Here's the function of a post route where i redirect to another get route:

return \Redirect::route('publicReservacionPasoDos', ['comidas' => $comidas, 'bebidas' => $bebidas]);

The other route controller's function is this:

public function pasodos()
{

    $horas = [
        '4:00',
        '4:30',
        '5:00',
        '5:30',
        '6:00',
        '6:30',
        '7:00',
        '7:30',
        '8:00',
        '8:30',
        '9:00',
        '9:30',
        '10:00',
        '10:30',
        '11:00',
        '11:30',
        '12:00',
    ];

    return view('Club.reservacion.paso2');

}

If i run the code as is, it outputs an exception of some parameters i use in the views...



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1LBcght
via IFTTT

What's the best way to work with personal modules/repositories/libraries in Laravel 5?

What's best aproach to work with modules in Laravel5?

For sample, i want create a personal modules to reuse in my projects, like:

User Profile Admin Message

I trying pingpong but have some problem with migrations, seeds for sample.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1Krw7kB
via IFTTT

Stripe - No API key provided (Laravel 5.1)

I have problem with providing the Stripe API key. Everything is included, packages, all dependencies...

The error message I get: No API key provided. (HINT: set your API key using "Stripe::setApiKey()". You can generate API keys from the Stripe web interface. See https://stripe.com/api for details, or email support@stripe.com if you have any questions.

Controller:

    public function upgradeBronze() {

        $bid = Session::get('builderId');

        Stripe::setApiKey(env('KEY_SECRET'));
        $token = $_POST['stripeToken'];

        // Create the charge on Stripe's servers - this will charge the user's card

        try {

            $user = \App\User::find($bid);
            $user->subscription('monthly')->create($token);
            return Redirect::route('builders-packages');

        } catch(\Stripe\Error\Card $e) {
            return Redirect::route('builders-packages');
        }

}

Error SS: http://ift.tt/1N17X2f



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1Jr97A7
via IFTTT

How to read binded model value to laravel route

I understood to bind model object to laravel route. But how to read the binded value to request in controller. furthur how can set controller and action for route once i use anonymous function.

Route::get('/{user_id}', function (App\Models\User $user) {
       // What to write here to return controll to usercontrollers profile action i.e. UserController@Profile... 
});



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1KrdWLY
via IFTTT

laravel 5 collection pull method prints nothing

my controller method returns this array, I know data is being returned

return view('bill')->with('itemarray',Menu::where('itemname','Apple Pie')->get());

my view is suppose to act on it like this but the print_r method prints the array but the td of the table has nothing in it and I am not getting an error

@if(isset($itemarray))
<table>
<tr>
<td>{{ $itemarray->pull('itemname') }} <!-- this prints nothing --> </td>
<td> {{ $itemarray->pull('itemprice') }} <!-- this prints nothing --> </td> 
</tr>  
</table>
<p>  {{  print_r($itemarray) }} <!-- this prints ok --> </p>
@endif



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1Enp0sj
via IFTTT

Is there a way to use Oauth2 and grand type PasswordGrant with refresh tokens?

Im using laravel for setting u an Oauth2 server. Im using the PasswordGrant type now. But i also want to get an refresh token. Does somebody know how to accomplish that?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1N0HnWU
via IFTTT

get other model which belongsTo current model

There are 3 tables (models): Booking, User, Hotel.

Booking belongsTo both User and Hotel.

User hasMany Booking, and Hotel hasMany Booking, too.

How to get all Hotels, which User has Booking for them? As any array (collection) which is iterateable.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1i7DIK7
via IFTTT

How to increment an item in Laravel collection?

$collection = collect([
    1 => ['sum' => 0, 'eaters' => 0],
    2 => ['sum' => 0, 'eaters' => 0],
    3 => ['sum' => 0, 'eaters' => 0],
    4 => ['sum' => 0, 'eaters' => 0],
    5 => ['sum' => 0, 'eaters' => 0]
]);

$collection[1]['sum'] += 5;

When i try to add something i get Indirect modification of overloaded element of Illuminate\Support\Collection has no effect. I think this is something to deal with ArrayAccess, but i'm not familiar with this...



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1LGmpfF
via IFTTT

How to increment an item in Laravel collection?

$collection = collect([
    1 => ['sum' => 0, 'eaters' => 0],
    2 => ['sum' => 0, 'eaters' => 0],
    3 => ['sum' => 0, 'eaters' => 0],
    4 => ['sum' => 0, 'eaters' => 0],
    5 => ['sum' => 0, 'eaters' => 0]
]);

$collection[1]['sum'] += 5;

When i try to add something i get Indirect modification of overloaded element of Illuminate\Support\Collection has no effect. I think this is something to deal with ArrayAccess, but i'm not familiar with this...



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1LGmpfF
via IFTTT

PHP Laravel - Query Scope - Where ids contain a value

I have two tables and models:

1) Files

2) Visits

using query scope, I can get the total number of visits from particular dates:

public function scopeByDate($query, $start_date, $end_date)
{
    return $query->whereHas('visits', function($q) use ($start_date, $end_date)
    {
          $q->whereBetween('created_at', array($start_date, $end_date));
    });

I can do that and this returns all of the files that have visits and these visits are made on a particular date.

As there is a relationship, I can, for each of of these returned files, get the visits by doing $results = Files::ByDate($start, $end)

The problem is that, this returns all of the visits by all of the users on this day. Let's say that I have 10 files and in that day, 5 of them are visited by user 1 and user 2 I want to limit to only showing the visits from user 1

NOTE: Inside the "Visits" there is a field called "user_id"

Is this possible? The users will be contained inside an array. $users = [1, 2, 3, 4] as an example



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1Jo2gFi
via IFTTT

Multisite CMS in Laravel 5.1, one backend, same server, folders, assets & general structure concerns

I´m just starting to learn Laravel and decided to build a new version of my current CMS system with Laravel 5.1. It will be a CMS with one admin and multiple sites.

I figured that since each site will be using different assets in the public folder, I would need to create different public folder for each app.

So instead of 'app/public', I have 'app/sites/Admin' with it´s own unique css files, images, etc. I´ve already built the Admin part, with it´s proper views, assets, models, controllers, etc, and it´s (apparently) working fine.

So when I started developing the "Time da ANABB" site, I followed the same process: created it´s own controllers in it´s own folder, it´s own views, etc.

But when I tried it out, the route does point to the proper view, but all my links to CSS, imgs, etc are broken. When I output {!! public_path() !!} on this site´s view, I get it point to "C:\Users\Martin\Dropbox\www\sistema-lengro\public"

So I´m not sure if I need to config a different public folder for each site (and if that´s the right thing to do!) or if I´m all wrong... Again, this is basically my first major project in laravel...

Some of my configs are:

I´m using Virtual Hosts and route groups to address each request, as in:

//Admin Route::group(['middleware' => 'auth', 'domain' => 'dev.sistema', 'namespace' => 'Admin'], function () { Route::get('admin', function () { return view('admin.painel'); }); }

//Site Route::group(['domain' => 'dev.timedaanabb', 'namespace' => 'TimeDaAnabb'], function () { Route::get('/', function () { return view('sites.timedaanabb.pages.home'); }); });

I´ve also created a controllers folder for each, like 'app/Http/Controllers/Admin' and 'app/Http/Controllers/TimeDaAnabb'. For the Models, will be 'app/Admin/Users.php', for example.

I don´t know if that´s the best approach, but it´s working fine so far.

Thank you in advance!



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1UhtHpu
via IFTTT

Bidrectional many 2 many morph models in Laravel

I have 4 different models: - People - Cars - Offices

So there are many2many relationships between all 3:

People <-> Cars
Cars <-> Offices
People <-> Offices

Is there a way I can define a single Pivot Table with double morph, having a MySQL table like this

- id
- target_id
- target_type
- source_id
- source_type

This way I could add any new model it comes into the picture.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1JnYeNq
via IFTTT

Laravel5 - Get selected column from relation

I am playing with Laravel5.

I have two model User & Items. And relation is User hasMany Items

I want to retrieve selected column from Items.

For example hasMany return [] (empty array of items)

 User::with(['items'=>function($q){

           $q->select(['name','desc']);
       }])
       ->find($id);

Above example return empty items array but if i change this relation to User hasOne Item then it works.

hasOne return only two column name & desc

 User::with(['item'=>function($q){

           $q->select(['name','desc']);
       }])
       ->find($id);



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1F2l4Iv
via IFTTT

How can I apply transaction block across model methods?

I am making Db changes within controller by putting this transaction block:

DB::transaction(function () use($request) {
   $user = new User();
   $user->first_name = $request->input('first_name');
   $user->last_name = $request->input('last_name');
   $user->save();

  if($request->session()->get('title')!=''){
       $result = $project->add($request->session()->get('title'),$request->session()->get('summary'),$request->session()->get('files'));
DB::commit();
});

add() is defined as:

public function add($title,$summary,$files){

        dd('In model: '.$title);
        $this->title = $title;
        $this->summary = $summary;
        $this->files = $files;
        if($this->save())
        {
            dd($this->id);
            return $this->id;
        }
        else
        {
            dd('Not Saved');
            return -1;
        }

    }

The issue is, it's not storing $project object related info where add is a model method.

Can't I apply Transaction like that?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1Uh6Lqp
via IFTTT

Laravel authentication route

I've a route with a parameter that´s an int. When a user goes to for example localhost/public/article/1 I want to show that article. But I don't want to show for example localhost/public/article/2 because that's from someone else. How do I do this? So I only want to show an article if the person is allowed to see it.

(The person is logged in)



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1MZlw28
via IFTTT

Laravel 5.1 Nayjest Grids(pagination issue)

I have recently started using Laravel 5.1. Everything is working well except this extension. I have tried to use pagination, but whenever I click on pagination buttons it redirects me to a 404 page.

This is how I set up the Nayjest Grid:

$query = (new Translations)
                    ->newQuery();
$cfg = (new GridConfig())
                    ->setDataProvider(
                            new EloquentDataProvider($query)
                    )
                    ->setPageSize(5)

This is how pagination links look like: localhost/application/public/dashboard/translations/?a4beae7c03b096d9[page]=2.

Everything is ok, but when I get to this page the headers look like this:

Remote Address:[::1]:80 Request localhost/securitymatrix/public/dashboard/translations/?a4beae7c03b096d9[page]=2 Request Method:GET Status Code:301 Moved Permanently (from cache)

and I get redirected here: localhost/dashboard/translations?a4beae7c03b096d9[page]=2 where I have these headers:

Request localhost/dashboard/translations?a4beae7c03b096d9[page]=2 Request Method:GET Status Code:404 Not Found (because that url does not exist)

Hope I can find a good reason why that redirect occurs. Also if you can give me an example or explain how to rewrite the url so I can simply have ?page=x I would be gratefull.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1MZlw26
via IFTTT

Laravel Routing: page you are looking for could not be found

I have a defined a rout in Laravel but when i call the route I Get 404 (Sorry, the page you are looking for could not be found.)

The Route is: einlagerungen/{$paletten_id}/bei_paletten_id

Route Definitions

Route::get('/', function () {
    return view('welcome');
});

Route::get('einlagerungen/{$paletten_id}/bei_paletten_id', [
   'as'=>'einlagerungen/bei_paletten_id', 'uses'=>'EinlagerungRestController@beiPalettenId'
]);

Controller Code

class EinlagerungRestController extends Controller
{
    ...

    public function beiPalettenId($paletten_id)
    {   
        return "it works";
    }

    ....

}



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1NLf3qG
via IFTTT

Laravel 5 How to perform validation in Controller to check for specific data in data collection

I want to perform custom validation in laravel 5, here is the concept. I have a category controller in which i want to delete a particular category. If category contains any other sub category i want to show validation error in laravel 5. For this concept i have create the program, but the program does not perform required validation. I am getting varies error like valiable not found or validation not performing or Undefined variable: struct. Below is the code that i am using to do that.

CategroyController destroy function, to delete record.

public function destroy(Request $request)
    {
        if(\Request::ajax()){
            $validator = \Validator::make($request->all(), array());
            $data = Configuration::findTreeParent($request->input('id'), 'Category');
            $selected = $request->input('id');
            foreach($data as $struct) {
                $validator->after(function($validator) {
                    if ($selected == $struct->id) {
                        $validator->errors()->add('field', $request->input('configname').' cannot be assigned to its child category.');
                    }
                });
            }
            if ($validator->fails()) {
                return $validator->errors()->all();
            } else{
                return \Response::json(['response' => 200,'msg' => $validator->fails()]);
            }
        }
    }

Please look into and help me out from this problem.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1Jnr54o
via IFTTT

jeudi 27 août 2015

Check if session array has given value or not in Laravel 5

In Laravel 5, I have session array named 'rights' containing array of values as below:

array:3 [
  0 => {#319
    +"rightid": 4
  }
  1 => {#320
    +"rightid": 5
  }
  2 => {#321
    +"rightid": 6
  }
]

Now, I want to check if this session array has 'rightid' = 4. I've tried this:

@if (Session::has('rights.rightid', '4')) Hello @endif

But its not working. Can anyone please help.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1F1KfLe
via IFTTT

Errors while using a laravel 5 boilerplate

I want to use http://ift.tt/1Lux1dt as a starting point for my Laravel project, but when I do composer install i get the following errors.

Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for guzzle/guzzle v3.9.3 -> satisfiable by guzzle/guzzle[v3.9.3].
    - guzzle/guzzle v3.9.3 requires ext-curl * -> the requested PHP extension curl is missing from your system.
  Problem 2
    - Installation request for stripe/stripe-php v1.18.0 -> satisfiable by stripe/stripe-php[v1.18.0].
    - stripe/stripe-php v1.18.0 requires ext-curl * -> the requested PHP extension curl is missing from your system.
  Problem 3
    - guzzle/guzzle v3.9.3 requires ext-curl * -> the requested PHP extension curl is missing from your system.
    - league/oauth1-client 1.5.0 requires guzzle/guzzle 3.* -> satisfiable by guzzle/guzzle[v3.9.3].
    - Installation request for league/oauth1-client 1.5.0 -> satisfiable by league/oauth1-client[1.5.0].

How to resolve this?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1LFju78
via IFTTT

check unique username when updating user details jquery modal

i'm using jQuery modal for user create and update for my laravel project. when creating new user im checking the username availaibilty. but that function doesnot support with update , when user save data without changing username it gives usernam availble error . please advice how to fix

my controller,

public function checkUsernameAvailability() {

$user = DB::table('users')->where('username', Input::get('username'))->count();

if ($user > 0) {
    $isAvailable = FALSE;
} else {
    $isAvailable = TRUE;
}

echo json_encode(
    array(
        'valid' => $isAvailable
    ));

}

jQuery modal

                        username: {
                            validators: {
                                notEmpty: {
                                    message: 'The Username field is required'
                                },
                                rules : {
                                    username : { alphanumeric : true }
                                },
                                remote: {
                                    url: "{{ URL::to('/checkUsername') }}",
                                    data: function (validator) {
                                        return {
                                            username: validator.getFieldElements('username').val()
                                        }
                                    },
                                    message: 'The Username is not available'
                                },
                                stringLength: {

                                    max: 100,
                                    message: 'The Username must be  less than 100 characters long'
                                }
                            }
                        },



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1NKQhXI
via IFTTT

AJAX post not sending data to laravel controller

Maybe this is a very common topic, but i can't find any solution!, the app i'm developing is under Laravel 5.0, i need to send some data from jquery ajax to a laravel controller, i've followed this tutorial to post data using ajax, i've followed the steps and made the global configuration, so that i have a meta with the csrf token, when i send the post request to a url using ajax, it just sends the token!! but nothing of the data i give it to send!

Here's my ajax func (i'm using dummy data to test it):

        $.ajax( {
            url        : '/reservacion/paso-uno/enviar',
            method     : 'post',
            data       : { name: "John", location: "Boston" }
        } );

but when i dd(\Request::all()); in the post func i only get the token, also if i check the headers form data i only get this:

data sent through the post

Here's a complete image of the headers: headers

Here's the meta tag with the csrf:

<meta name="_token" content="{{{ csrf_token() }}}"/>

And here's the global ajax setup:

$.ajaxSetup({
                headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
            });



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1PBCykt
via IFTTT

Ajax not firing inside Modal Popup

Currently I have a button to view cart contents as such:

<a href="#" class="btn btn-info" role="button" data-toggle="modal" data-targets="showvendorcart1" data-target="#showvendorcartModal" data-async="true" data-cache="false" data-endpoint="vendor/showcart/{{$vendorid}}">SHOW CART</a>

data-target is for my modal

data-targets is for the body of my modal after the ajax endpoint returns a response

My Ajax code is as follows:

$('a[data-async="true"]').click(function(e){
    e.preventDefault();
    var self = $(this),
        url = self.data('endpoint'),
        target = self.data('targets'),
        cache = self.data('cache');

    $.ajax({
        url: url,
        cache : cache,
        success: function(data){ 
            if (target !== 'undefined'){
                $('#'+target).html( data['response'] );
            }
        }
    });
});

(courtesy of jQuery and data-attributes to handle all ajax calls?)

Now once the modal dialog popup has appeared I have some grid items inside a table such as:

<table id="itemstable" class="table table-striped table-bordered">
    <thead class="fixed-header">
        <tr>
            <th>QTY</th>
            <th>SKU</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>' . $v->qty . '</td>
            <td>' . $v->sku . '</td>
            <td><a href="#" class="btn btn-danger" data-targets="showvendorcart1" data-async="true" data-cache="false" data-endpoint="vendor/removecart/' . $v->id . '">&nbsp;X&nbsp;</a>
        </tr>
    </tbody>
</table>

The problem I'm running into is I have another ajax endpoint call for each table line item but this time when I click it, the Ajax isn't firing at all. I looked at my browsers inspector but not even an error or attempt.

Am I missing something here because it's practically the same code I ran to get the popup and show the response in the body but now the only difference is I'm doing it inside the modal.

Your help is appreciated!



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1PBrBj5
via IFTTT

Creating dynamic labels in Laravel and passing variables to them

I have a form that creates a project. A project can have a few external links.

For example, it can have a link to Behance, deviantART, YouTube, Facebook and so on.

Some might not have any links at all.

If a project has Behance or deviantART or Facebook link, then when viewing the project, it should say:

View [project name] on [social network name].

If it has a link to YouTube, it should say:

Watch [project name] on YouTube.

And some other link can have custom 'labels' so to say.

Of course I could do an if statement, but I believe there's an easier way to do this using something like Lang maybe? The only thing I don't understand is - how can I pass that [project name] to the Lang option?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1JzHqSJ
via IFTTT

Validator for varying amounts of data

I have a form with a varying number of fields. It is necessary to make a validator for this form, which verifies that all the fields between them have different values.

<form method="POST" action="url/action">
 <input type="hidden" name="_token" value="{{ csrf_token() }}">
     @for ($i = 0; $i < $num; $i++)
         <div class='form-group'>
             <label>
                 Property №{{ $i+1 }}:
                 <select name="property{{ $i }}">
                     @foreach($properties as $property)
                         <option value="{{ $property->id }}">{{ $property->name }}</option>
                     @endforeach
                 </select>
             </label>
         </div>
     @endfor
 <input type="submit" class="btn btn-primary" value="Добавить">
</form>

So, all values of select must be different from each other. Help write a validator, please.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1hiEkMc
via IFTTT

make a post request from jquery to laravel controller

I'm trying to make a post request to a Laravel Controller, but when i send the data through ajax it doesn't work, here are my scripts:

Here's the form:

<form >
    <label for = "cantidadpersonas" >Cantidad de personas</label >
    <input id="personas" type = "text" placeholder="#" >
    <br ><br ><br >

    <label for = "comidas" >Seleccione los platillos que desea reservar</label >
    <br ><br ><br >
    <div id="comidas" class="owl-carousel owl-theme">

        @foreach($platos as $plato)
            <a class="item opcion comida">
                <p class="hidden">{{ $plato->id }}</p>
                <img id="{{ $plato->id }}" class="img" src = "{{ asset('club/img/gallery/gallery1.jpg') }}" alt = "{{ $plato->nombre }}" >
            </a >
        @endforeach
    </div>
    <br ><br ><br >
    <div id="bebidas" class="owl-carousel owl-theme">
        @foreach($bebidas as $bebida)
            <a class="item opcion bebida">
                <p class="hidden">{{ $bebida->id }}</p>
                <img id="{{ $plato->id }}" class="img" src = "{{ asset('club/img/gallery/gallery2.jpg') }}" alt = "{{ $bebida->nombre }}" >
            </a >
        @endforeach
    </div>
    <br ><br >

    <button id = "enviar" >Siguiente</button >
    <br ><br ><br >
    <!-- /input-container -->
</form >

Here's the post function in laravel controller:

public function pasounoPost(){

        dd(\Input::all());

        if(\Request::ajax()) {
            $data = \Input::all();
            dd($data);
        }

    }

And here's my ajax code for click event on enviar button:

$("#enviar").click(function(){
        event.preventDefault();

        var bebidas = $('.clicked.bebida').map(function () {
            var $this = $(this);
            var bebida = {};
            bebida.id = $this.find('p.hidden').text();
            return { bebida: bebida};
        }).get();

        var comidas = $('.clicked.comida').map(function () {
            var $this = $(this);
            var bebida = {};
            bebida.id = $this.find('p.hidden').text();
            return { bebida: bebida};
        }).get();

        var bebidas_json = JSON.stringify(bebidas);
        var comidas_json = JSON.stringify(bebidas);

        $.ajax( {
            type:  'post',
            url  : '/reservacion/paso-uno/enviar',
            data : { bebidas: bebidas_json },
            success:  function () {
                console.log('Hecho');
                console.log(bebidas_json);
            }
            //dataType: "json"
        } );

    });

And here are my routes:

Route::get('/reservacion/paso-uno', [
        'as' => 'publicReservacionPasoUno',
        'uses' => 'ReservacionCtrl@pasouno'
    ]);

    Route::post('/reservacion/paso-uno/enviar', [
        'as' => 'publicPostReservacionPasoUno',
        'uses' => 'ReservacionCtrl@pasounoPost'
    ]);

I get the success function when i click the button, but i don't get redirected to the next view... that is declared in the laravel controller.

What i need is to send data to the pasounoPost function from jquery ajax, and redirect to another route and send the data sent from ajax.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1JmpA6z
via IFTTT

Laravel 5: Ajax Post 500 (Internal Server Error)

I'm trying to submit data to the database via ajax. The submit article page works fine without ajax. I've added console.log() just to see if anything is going through, but instead I'm getting this error:

POST http://localhost/laravel-5/public/articles/create 500 (Internal Server Error)

What's wrong with my code? Is it the javascript or the controller?

EDIT: I'm getting this in laravel.log

exception 'Illuminate\Session\TokenMismatchException' in C:\xampp\htdocs\laravel-5\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken.php:53

Route

Route::resource('articles', 'ArticlesController');

Controller

public function store(Requests\ArticleRequest $request)
    {

        $article = new Article($request->all());
        Auth::user()->articles()->save($article);

        $response = array(
            'status' => 'success',
            'msg' => 'Article has been posted.',
        );
        return \Response::json($response);
    }

jQuery

$(document).ready(function() {
    $('#frm').on('submit', function (e) {
        e.preventDefault();
        var title = $('#title').val();
        var body = $('#body').val();
        var published_at = $('#published_at').val();
        $.ajax({
            type: "POST",
            url: 'http://localhost/laravel-5/public/articles/create',
            dataType: 'JSON',
            data: {title: title, body: body, published_at: published_at},
            success: function( data ) {
                $("#ajaxResponse").append(data.msg);
                console.log(data);
            }
        });
    });

View

<link rel="stylesheet" href="http://ift.tt/1K1B2rp">

<h1>Write a New Article</h1>

<hr>

{!! Form::open(['url' => 'articles', 'id' => 'frm']) !!}
    <p>
        {!! Form::label('title', 'Title:') !!}
        {!! Form::text('title') !!}
    </p>

    <p>
        {!! Form::label('body', 'Body:') !!}
        {!! Form::textarea('body') !!}
    </p>

    <p>
        {!! Form::label('published_at', 'Date:') !!}
        {!! Form::input('date', 'published_at', date('Y-m-d'), ['class' => 'form-control']) !!}
    </p>

    <p>
        {!! Form::submit('Submit Article', ['id' => 'submit']) !!}
    </p>
{!! Form::close() !!}

<h3 id="ajaxResponse"></h3>

@if($errors->any())
    <ul>
    @foreach($errors->all() as $error)
        <li>{{ $error }}</li>
    @endforeach
    </ul>
@endif

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="{{ URL::asset('assets/js/ArticleCreate.js') }}"></script>

});



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1U8GBvi
via IFTTT