mercredi 31 août 2016

Quality must range from 0 to 100 - Intervention Laravel 5.x

I'm using intervention/image 2.3. When I try to upload an image I got the following error :

InvalidArgumentException in AbstractEncoder.php line 212

Quality must range from 0 to 100

Below is my code for that :

$file = Input::file('image');
$filename = time() . '.' . $file->getClientOriginalExtension();
Image::make($file)->resize(50, 50)->save(storage_path() . DIRECTORY_SEPARATOR . 'uploads', $filename);

Any single guidance will help me alot.



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

Laravel 5 - How to add custom msgs to Validation?

Im trying to figure out how to quickly add error messages per field in Laravel 5. Here is what I got:

$validator = Validator::make($this->req->all(), [
'email_add' => 'required|email|max:100',
'pass' => 'required|max:20',
]);

So how do I put a message directly here for each field validated above?

like "You forgot Email Address" and "Password is Required"?

(without writing a mars rover program for 1 simple task. Like the usualy laravel 5 stuff of artisan make new something useless, add 2 name spaces, 3 middlewares, 5 classes, 7 functions and then finally override error messages!!)



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

Laravel5: Form-model binding - Radio buttons auto select causing problems when creating new record

I'm using Form-Model binding and the same view partial for both creating and editing a user.

While trying auto-select radio buttons based on db values upon Edit, The correct item selects by default, which is the expected result. But when I try creating a new user using the same form partial, it gives an error Undefined variable: user because we didn't pass a $user variable on the create method, which seems unnecessary. How do I fix this?

Controller Methods:

public function create()
    {
        return view('backend/users/create');
    }
public function edit(User $user)
    return view('backend/users/edit', compact('user'));
}

Form radio buttons:







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

Switching back from session across sub domains to session based on sub domains

My site is using session across sub domain (domain => '.domain.com'). I want to change it to session based on sub domains so I changed the config to domain => null. Then I got the problem on users that logged in before. Although they already logged out and logged in again, the session is still across sub domains. It works for users never logged in to the site before. Please help me. Thanks. Btw, when I clear all the cookies on the site manually. It also works.



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

POST data from android using Volley to Laravel5

I'm having problems on what URL to be used to link to the php scripts in Laravel5 which I'm running at localhost at the moment. I have created a function in my controller to handle the request. Here is the function:

    public function mobile_validator(Request $request) {
    $method = $request->method();
    if($method == 'POST') {
        $username = $request->username;
        $password = $request->password;
        $user = DB::table('users')->get();
        foreach($user as $i) {
            if($username == $i->email and $password == $i->password) {
                return 'success';
            }
            else {
                return 'failure';
            }
        }
    }   

I have also created a route in my route.php.

Route::get('/mobilevalidator', 'AuthController@mobile_validator');

This is my URL in android:

private static final String LOGIN_URL = "http://ift.tt/2ca9c06";

Now when I login in my app it displays the error com.android.volley.timeouterror

Is the URL correct in defining the php script in Laravel?



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

How to populate edit form fields in laravel 5.3

I have a problem in populating edit form fields in my first Laravel 5.3 application. In examples I have found online, they have used Form facade to do it. However, I prefer to use plain html.

This is my controller action

public function edit()
{
    $profile = Profile::find(Auth::user()->id);
    return  view('profile.edit', ['profile' => $profile]);
}

In my view file I have a form like this

<form method="POST" action="">

<input id="name" type="text" name="name" value="">
...
</form>

Problem is, above input field is not populated with the value of the $profile->name.

I can get it to work, setting the value attribute like



Since I'm new to Laravel framework I want to know if there is a better way to do that.



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

VirtualBox/Vagrant Error on 'vagrant up' command

I am trying to set up my Laravel Ubuntu Developement environment with Homestead but I keep getting this error when I enter the 'vagrant up' command in the vagrant CLI. It's fine up to the point of "default: Booting VM":

machine@User:~/Homestead$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Checking if box 'laravel/homestead' is up to date...
==> default: Clearing any previously set forwarded ports...
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
    default: Adapter 2: hostonly
==> default: Forwarding ports...
    default: 80 (guest) => 8000 (host) (adapter 1)
    default: 443 (guest) => 44300 (host) (adapter 1)
    default: 3306 (guest) => 33060 (host) (adapter 1)
    default: 5432 (guest) => 54320 (host) (adapter 1)
    default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Running 'pre-boot' VM customizations...
==> default: Booting VM...
There was an error while executing `VBoxManage`, a CLI used by Vagrant
for controlling VirtualBox. The command and stderr is shown below.

Command: ["startvm", "b7d57380-a06d-4474-ad3a-edfebc787b87", "--type", "headless"]

Stderr: VBoxManage: error: The virtual machine 'homestead-7' has terminated unexpectedly during startup with exit code 1 (0x1)
VBoxManage: error: Details: code NS_ERROR_FAILURE (0x80004005), component MachineWrap, interface IMachine

  • OS:================>Ubuntu 16.04.1 LTS (Xenial Xerus)

  • vagrant version:===>Installed Version: 1.8.5/Latest Version: 1.8.5

  • VirtualBox version:>5.1.4

  • laravel/homestead:=>0.5.0

  • Secure Boot:=======>OFF



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

How to remove empty lines in my console Laravel 5.3

I have a laravel installation, the console was working fine at start, then after a while i must have done something that made the console spit some extra empty lines. Here is what it looks like

D:\PATH_TO_MYAPP>php artisan migrate:refresh --seed






                                                Migration table not found.
Migration table created successfully.
...

How do i remove these extra lines?



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

Exclude white space from Elasticsearch when searching

I've got elastic search working great on my site, I can search pretty descent. My problem is when i do a search on something like HipHop vs Hip Hop, or cellphone vs cell phone, my results for the first text query won't appear . I want to make it so that if a user searches either word with or without a space, the results will be the same. here's what my code to search looks like. I'm using Laravel 5

 $q = $request->input('q');
  $response = $client->search([
        'index' => 'users',
        'type' => 'user',
        'body' => [
            'query' => [
                'bool' => [
                    'should' => [
                        ['match' => [ 'text' => $q ] ],
                    ],
                ],  
            ],
        ],
    ]);



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

How to do statistics about a pivot table

I successfully defined a many-to-many relation:

// in model 'Label'
public function pictures() {
    return $this->belongsToMany('App\Picture');
}

// in model 'Picture'
public function labels() {
    return $this->belongsToMany('App\Label')->withTimestamps();
}

With this I can - for instance - easily retrieve the labels of a specific picture

$picture = Picture::find(1);
$labels = $picture->labels()->orderBy('name')->get();

But now I want to figure out how often each label is used. I could walk through all pictures, using the above code, but this would be inefficient.

Is there a way to do this in a better way and access the pivot table directly? ... something like

$n = DB::getPivot('App\Label', 'App\Pictures')->count()->groupBy('App\Label');

?



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

Whitespace not caught by Laravel validation

I'm trying to validate a password input field, and spaces are not getting caught by the validator. The password field should be a minimum of 6 characters, and the regex should allow spaces within a password, but not at the beginning or end (I've confirmed that this works outside of the validator).

When a user enters in 1+ spaces into the password field (but no other characters) and submits, the validator fails to catch it (i.e., " " isn't caught by the validator).

Here's what my validator looks like:

$this->validate($request, [
    'name' => 'required|max:255|alpha',
    'password' => 'http://regex:/^[^\s]+(\s+[^\s]+)*$/|min:6|confirmed',
]);



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

Iphone HTML form file upload

Has anyone found a work around for uploading multiple images through IOS and HTML web forms?

Each file is uploaded as image.jpeg, but the problem is, that it never sends the data for the other image.

If done with multiple, you get an empty array.

If you use another file box, it does not send anything except the image name (again image.jpeg)

Testing can be found here: http://ift.tt/2bHZNeY

It uses jQuery for the first 2 parts of the form and then an normal post for the 2nd part (Have tried multiple ways of getting the image up)

THis is only an IOS problem works fine on all desktops and Andriods.



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

Laravel 5.2 Routing Session

My routes look like this:

Route::put('session/userinfo', function (Request $request) {
  $request->session()->put('userinfo', 'value');
});
Route::get('session/userinfo', function(Request $request) {
  return $request->session()->get('userinfo');
});

I've also tried this:

Route::put('session/userinfo', function () {
  session('userinfo', 'value');
});
Route::get('session/userinfo', function() {
  return session('userinfo');
});

and this:

Route::put('session/userinfo', function () {
  Session::put('userinfo', 'value');
  Session::save();
});
Route::get('session/userinfo', function() {
  return Session::get('userinfo');
});

None of these throws any errors, but I never receive any session info. I do have Route::group(array('middleware' => ['web', 'auth']) and also tried 'middlewareGroups' instead of 'middleware'. Nothing changes. Wtf do I have to do to utilize Session?



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

Getting Error while Overriding Password Reset Template Laravel 5.3

hello i have just started working on laravel 5.3 and soon came across this issue. Unlike 5.2, where we have hardcoded emails or some custom packages, here we are restricted to a single template.

So first of all i have updated the user model to include

public function sendPasswordResetNotification($token)
{
    $this->notify(new ResetPasswordNotification($token));
}

Then i have a notification file called ResetPasswordNotification and inside i have a

 public function toMail()
    {
        return (new MailMessage)
            ->line([
                'You are receiving this email because we received a password reset request for your account.',
                'Click the button below to reset your password:',
            ])
            ->action('Reset Password', url('password/reset', $this->token))
            ->line('If you did not request a password reset, no further action is required.');
    }

But i want to include a custom email template views and send data to these views like how we did earlier. Now to impliment the old style in the new laravel we have to adopt it like this.

return (new MailMessage) ->view('emails.templates.layout5') ->data([ 'pageTitle' => 'Password Reset', 'logo' => $logo, 'topMenu' => 'TOP MENU', 'mainTitle' => 'Verify email to', 'subTitle' => 'Reset Your Password', 'image' => 'largeimg.png', 'content' => $content, ]);

But when i do this, i get an error

ErrorException in MailChannel.php line 44:
Trying to get property of non-object



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

How can I get the thumbnail/image and desciption of a foreign url, like facebook or twitter?

I want to create an application where users can share link from other websites and a thumbnail/image appear with a little description under it (something like facebook, twitter, reddit..), how can I get to recognize whether the user actually posted a link and automatically generate a thumbnail and an description from that website if it has one

I'm trying to do this with laravel!



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

Multiple get routes for same URI in laravel

I have routes set through resource controller...route-list

the route with the URI named as payments in the picture are working fine for resource called payment. But when I added

Route::get('payments', ['uses'=>'PaymentsController@retrieve', 'as'=>'retrieve']);

The route is not showing in route list as shown in the image.Please help



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

Laravel select 3 rows from the same table with different value for a specified column

In my database is stored a table called 'advertisement' with the following records:

id |   code      | position
 1 |   header1   | header
 2 |   header2   | header
 3 |   header3   | header
 4 |   footer1   | footer
 5 |   footer2   | footer
 6 |   banner1   | banner
 7 |   banner2   | banner

I need to pick only one record for each 'position'. For example an output could be:

 1 |   header1   | header
 5 |   footer2   | footer
 7 |   banner2   | banner

How can I achieve this?

Advertisement::where(...)->distinct()->get();

This didn't do the magic because it's giving me distinct values considering all the columns, not only 'position'



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

logging not working in laravel queue job

I have the below settings in my supervisor/conf.d/myconf.conf file :

[program:my-worker]

process_name=%(program_name)s_%(process_num)02d

command=php /var/www/html/artisan queue:work sqs --queue=my_queue_name --tries=3 --daemon

autostart=true

autorestart=true

user=root

numprocs=1

redirect_stderr=true

stdout_logfile=/var/www/html/storage/logs/mylogfile.log

I have give all permissions to storage/logs/mylogfile.log file. Not able to figure out why is it still not logging? Any help would be appreciated. Thanks.



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

Laravel 5.2 - Session flash data not set in service provider

I have created a frontend service provider for my app:

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Session;

class FrontendServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        view()->share('message', !is_null(Session::get('message')) ? '<div class="alert alert-success"><strong>Success! </strong>'.Session::get('message').'</div>' : '');
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

I am setting a flash message in the controller like so:

public function resend_welcome($token)
{
    $user_id = Crypt::decrypt($token);
    $user = User::findOrFail($user_id);
    if($user->meta->confirmed==1) {
        abort(404);
    }
    Event::fire(new UserRegistered($user));

    Session::flash('message', 'A new email has been sent.');

    return redirect(route('register.success', $token));
}

Then in my view I am trying to output $message like so:



The problem is $message is always NULL. If I use Session::get('message') in my view instead then it works and the flash message is displayed. Why is Session::get('message') always NULL in the service provider even though I have set it in the controller?



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

Issue with not being stored sessions (API App)

One of the methods within an API allows the user to switch subscriptions. An active subscription is kept in the sessions.

Conditions: To start off subscription id = 3

I make two following calls: Set subscription with subscription id = 10 Get current subscription and return should be 10

I did a run using "Postman" and when calling current subscription result was 10.

However, when using VB.NET current subscription returned id = 3. Additionally to that, when testing set subscription method I have returned active subscription after change took place and subscription has indeed changed but as we can see was lost shortly afterwards.



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

Laravel 5.2 swiftmailer library `_swiftmailer_init` function is not loading

I'm working in laravel 5.2 on PHP version 5.6.25. I'm getting issue with swiftmailer library to send emails. I'm getting this error when sending email on my live server

InvalidArgumentException in Response.php line 458: 
The HTTP status code "0" is not valid.

When I searched online regarding this issue. Then got solution for this to add one line vendor/swiftmailer/swiftmailer/lib/swift_required.php file.

require dirname(__FILE__).'/swift_init.php';

But this line is already added in this file. But inside a function which is loading using autoloading. Below is the code of this file

if (class_exists('Swift', false)) {
    return;
}

// Load Swift utility class
require dirname(__FILE__).'/classes/Swift.php';

if (!function_exists('_swiftmailer_init')) {
    function _swiftmailer_init()
    {
        require dirname(__FILE__).'/swift_init.php';
    }
}

// Start the autoloader and lazy-load the init script to set up dependency injection
Swift::registerAutoload('_swiftmailer_init');

It seems that last line Swift::registerAutoload('_swiftmailer_init'); is not working.

This issue is getting on live server.. But working properly on my local server and testing server also. My local server has '5.5.9' php version. Please help me on this.

Thanks in Advance.



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

laravel 5.2 Authentication Failure

    Hello Guys i am new to laravel. When the new user register with authentication i am this error message. How to resolve my problem
    The Authentication Failure with this error message. Illuminate\Auth\SessionGuard::login() must be an instance of Illuminate\Contracts\Auth\Authenticatable, instance of App\customer given.

        My controller is

          public function store(Request $request)
    {
        $user = new customer;
        $user->name=Input::get('name');
        $user->email=Input::get('email');
        $user->password=Input::get('password');
        $user->save();

        Auth::login($user);
        return redirect::home();
    }

        and my routes 
        Route::get('register', 'testing@index');
        Route::post('store', 'testing@store');
        Route::get('login', 'testing@create');
        Route::post('logout', 'testing@destroy');

and my register page is 

<form action="store" method="post">
        <label for="name">Name</label>
        <input type="text" name="name" autocomplete="off">
        <br>
        <label for="email">Email</label>
        <input type="text" name="email" autocomplete="off">
        <br>
        <label for="password">Password</label>
        <input type="text" name="password" autocomplete="off">
        <br>
        <input type="hidden" name="_token" value="">
        <br>
        <input type="submit" name="submit" value="Submit">
    </form>

Please help me guys how to register,login and logout with complete authentation. Please help me guys how to register,login and logout with complete authentation. Please help me guys how to register,login and logout with complete authentation. Please help me guys how to register,login and logout with complete authentation. Thanks you and welcome your suggestions.



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

Can I add the developer token dynamically in the code when using google adwords api instead of writing it in the auth.ini file?

I a developing a website that deals with different adwords account and each account has his own developer token , so is there any way to add the developer token in the same way as adding the client id using $user->SetClientCustomerId($id);



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

call a function after a column is changed

I would like to know when a column in my table is changed.

for example, if an user changed fist-name column , I would like to find out it (to call my custom function).

is there any function/library/plugin in laravel to help me ?



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

Class 'PhpParser\Parser\Php7' not found Laravel when using Mail

I had no problems since a week ago, now when I try to send a Mail via : Mail::queue('myemail', $data, function($message) use ($data){....});

I have the following error :

FatalErrorException in ParserFactory.php line 27:
Class 'PhpParser\Parser\Php7' not found

what can I do to solve this issue ? I'm using wampserver 3.0.4 and laravel 5.2



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

Filter out multiple where not like

I am trying to RTFM but cannot see where the list of possible where operators are listed. I only see the basic examples of >=, <> and like. Anyways, I want to filter out any results that match multiple patterns.

If I use

->whereNotIn('fieldName', ['exactString1', 'exactString2'])

Then I filter these exact strings from my results. However I want to filter out multiple patterns (NOT LIKE) rather than multiple strings.

I am using MySQL so I'm open to using a raw query is the query builder does not support this.



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

Laravel - Deleting a row (table)

I'm using laravel 5.2 and I'm studying the manipulation of datas with Eloquent. I have a table in which I need to delete a row with a button.

Problem : The server returns a route error (NotFoundHttpException)

Guideline : I watched this video https://www.youtube.com/watch?v=1EyoZhfZ2TY in order to inspire me for the datas.

Here is the Route (routes.php)

Route::delete('players&/{id}', 'PlayersController@deletePlayer');

Here is the template (players.blade.php) Pay attention of the last table data (td)

     <tbody>
    <?php
        foreach($players as $player) {
    ?>
    <tr>
        <td><?php echo $player->PLA_ID?></td>
        <td><?php echo $player->PLA_Name?></td>
        <td><?php echo $player->PLA_Surname?></td>
        <td><?php echo $player->PLA_Pseudo?></td>
        <td><span class="glyphicon glyphicon-pencil"></span></td>
        <td><a href="delete&<?php echo $player->PLA_ID?>"><span class="glyphicon glyphicon-trash"></span></a></td>
    </tr>
    <?php }
    ?>
    </tbody>

Finally the function (PlayersController.php)

    public function deletePlayer($id){

    Player::destroy($id);
    return redirect('players');
}

I will search on my side too and thank you for taking time on my problem =)

P.S. I need the best practices with this framework, so if you have some ideas that allow me to code better, I could help some beginners like me =)



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

Laravel 5 - Artisan::call('migrate',['--path' => $database_path."/migrations/new_migrations"]); not working

I am trying to execute migrations from the folder "new_migration" which is created in database/migration folder

$database_path = database_path();    Artisan::call('migrate',['--path'
=> $database_path."/migrations/new_migrations"]);

On local server its working fine.

my website hosted on forge server on which its not working, is there any permission issue?



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

supervisord superlance memmon not work

supervisord.conf

[eventlistener:memmon]
command=/usr/local/bin/memmon -p system_message_dispatch=35MB
events=TICK_60

[program:system_message_dispatch]
command                 = php /mnt/www/project/artisan queue:work --queue=system_message_dispatch --sleep=3 --tries=3 --daemon
process_name            = %(program_name)s_%(process_num)02d
numprocs                = 6
autostart               = true
autorestart             = true
stdout_logfile          = /tmp/supervisor_system_message_dispatch.log
stdout_logfile_maxbytes = 10MB
stderr_logfile          = /tmp/supervisor_system_message_dispatch.err.log
stderr_logfile_maxbytes = 10MB

my problem is: when the program system_message_dispatch's RSS exceed 35MB, this program don't restart, but memmon have response

supervisor> tail memmon
READY
RESULT 2
OKREADY
RESULT 2
OKREADY
RESULT 2
OKREADY



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

Can't delete session value in laravel5.2

I use these codes to stop multiple form submission.But it doesn't work. I found $form_token and $token were always the same. I had writted session(['form_token' => null]). But It doesn't work.Why?

// make token
function form_token()
{
    session(['form_token' => Str::random(40)]);
    return session('form_token');
}

//check token
function check_token($form_token, $token)
{
    if ($form_token == $token) {
        session(['form_token' => null]);
    } else {
        throw new RuntimeException('Do not submit multiple times');
    }
}

// middleware
public function handle($request, Closure $next)
{
    if (!in_array($request->method(), ['HEAD', 'GET', 'OPTIONS'])) {
        $form_token = $request->input('form_token');
        $token      = session('form_token');
        check_token($form_token, $token);
    }
}



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

mardi 30 août 2016

How to show Count Data in Laravel 5

Im new in Laravel, 5 hours i have tried to adding this function and im so confused. Case : I want to show count data in table "tb_surat" in dashboard (i used sximo) ex, if in "tb_surat" i have 12 row data. how to show this like "Total data : 12"

help me please, give me step by step to adding in controller or view or route or etc, i dont understand. thanks.



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

handle large database with cron job for remote api connection

I am newbie in Laravel n building a small project for my practise. there is one registration form and upto 100 registration done a day approx.

it return me status->pending of user.

Now my question come here that , php execution time for connection with remote Api is 30 second as per my knowledge.

then , how can i handle the cron job in such a condition where i need to call remote api for receiving the data for every user status if it becomes "accepted" or "rejected" or still in "pending"

i am struggling with this condition and my database structure like

userId - status - created_at - updated_at

I need to call it after 20 hours if possible for all user or every 4 hours if we cannot call them at once.

What will be the best practise to do it?



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

404 Error when Testing Request class validation through Chrome Postman Extension

Below is my Controller Action method. You can see I passed a param of Request Class to validate before going to save the data in database

public function store(RoleRequest $request)
{
}

My Request class is below.

class RoleRequest extends Request
{
    private $Role;

    public function __construct(IRole $_role) {
        $this->Role = $_role;
    }        
    public function authorize()
    {
        return true;
    }    
    public function rules()
    {
        return [
            'Role' => 'required|max:20|min:4,
        ];
    }    
}

Above code works perfectly when I run it through web page.

I created one more controller for API to Send save request. Below is the code

class RoleApiController extends Controller
{
    public function store(RoleRequest $request)
    {

    }
}

Issue comes, when I type just 1 char for role name and the Request class impose validation and I get 404 error This time I am sending request from Postman Extension in Chrome.



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

nusoap exception Illegal argument invoking

the project made in laravel, call via SOAP to Web service in java, using nusoap complement

$factura=Facturas::find($id);
    $folio=$factura->folio.'L';
    $dataws=[
    'serie'=>$factura->serie,
    'folio'=>intval($folio),
    'rfcRecibido'=>$factura->distribuidor->rfc,
    'key'=>'xxxx-xxxx-xxx-xxxx-xxxx'
    ];
$websc = new nusoap_client('http://ift.tt/2bzMmkc');
    $error = $websc->getError();

when call function cancelCFD

$result = $websc->call('cancelaCFD', $dataws);
        if ($websc->fault) {
        echo '<h3>Error</h3><pre>';
        print_r($result);
        echo '</pre>';
            echo response()->json(array('success'=>false,'codigo'=>$result));
    }

the ws sends this

{"faultcode":"soap:Client","faultstring":"Illegal argument invoking 'com.tralix.xsa.manager.cancel.ws.ICancelService.cancelaCFD(java.lang.String, java.lang.Long, java.lang.String, java.lang.String)': java.lang.ClassCastException@40751341"}}

how make the integer value (folio) to long



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

Query an array passed from a pivot table inside a foreach loop in Laravel

I am looking to create a following system similar to Twitter, as far have come up with below.

I am looking to query the results of a foreach loop to see the current user is already following the profile the current user is on.

Particularly this part is failing:

if($following->pivot
         ->where('follow_id', $account)
         ->where('user_id', $user)){
         echo 'Already followers';

Resulting in "Already followers" every time when the database says otherwise.

$account = the current pages id
$user = the auth id

He is the full code:

if($user !== $account){ 
            echo "Not user profile";
                foreach ($profiles->follow as $following) {
                    if($following->pivot
                        ->where('follow_id', $account)
                        ->where('user_id', $user)){
                            echo 'Already followers';
                    }
                    else
                    {
                        echo 'follow route link';
                    }}}
        else
        {
            echo 'User Profile';         
        }



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

How to Rewrite URL in web.config file to hide index.php in url like http://ift.tt/2bP69Kj?

I have a Laravel app hosted on a .net panel, which works fine if installed in the root. But I have to use it inside of two sub-directories after root, i.e. it's installed in root/dir1/dir2/app. Now below is my current code in the web.config file which works fine if the app is installed directly in the root directory:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="Move to index.php">
                    <match url=".*" />
                    <conditions>
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="index.php/{R:0}" logRewrittenUrl="true" />
                </rule>
            </rules>
        </rewrite>
         <httpProtocol>
            <customHeaders>
                <add name="X-UA-Compatible" value="IE=11" />
            </customHeaders>
        </httpProtocol>
    </system.webServer>
</configuration>

So, currently, http://ift.tt/2cp9FzS works, but I need it to be like http://ift.tt/2bP7QqM , is it possible? If so, please explain your answer as much as possible. Thanks.



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

Laravel 5.3 SubstituteBindings middleware with withoutMiddleware issue

Since Laravel 5.3, the route implicit binding works as middleware called SubstituteBindings. I was worked with Laravel 5.2 and upgraded to 5.3 now.

I have custom middlewares in my application, and in my tests I sometimes need to disable them. So until now I used $this->withoutMiddleware() in the test method. But since the update to Laravel 5.3, withoutMiddleware stops the route implicit binding, and all my tests fails.

I don't know if this consider as bug, but it is a huge problem for me. Is there any way to set the SubstituteBindings middleware as mandatory middleware that withoutMiddleware will not disable? How can I still use implicit binding and test my tests without other middlewares?



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

Delete user and user created data in Laravel 5

I have a site where users can create posts and messages. I want it so that when a user delete's their profile, that all user's posts and messages will be deleted as well. I have a users, messages, and posts table. I was thinking of just doing something like

User::destroy(Auth->user()->id); //to delete user
Message::where(user_id, Auth->user())->delete(); //to delete al messages from that user
Post::where(user_id, Auth->user())->delete(); //to delete all posts from that user

Is this the best way, or is there a more elegant option? Do i need to basically search all my tables for that user_id then delete each row?



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

Laravel uploading multiple images doesn't work, also mimes don't

I'm trying to upload images in Laravel using this code:

public function postAddPictures(Request $request)
    {

      // getting all of the post data
      $files = $request->file('cover_image');
      // Making counting of uploaded images
      $file_count = count($files);
      // start count how many uploaded
      $uploadcount = 0;
      foreach($files as $file) {

        $messages = [
            'cover_image.required' => 'U moet een afbeelding opgeven.',
            'cover_image.image' => 'De bestanden moeten een afbeelding zijn (jpeg, png, bmp, gif, or svg).',
            'description.required' => 'U moet een beschrijving opgeven.'
            ];

        $rules = [
            'cover_image' => 'required',//|mimes:png,gif,jpeg,jpg,bpm,svg
            'album_id' => 'required|numeric|exists:albums,id',
            'description' => 'required'
        ];

        $validate = ['file'=> $file, 'description' => $request->get('description'), 'album_id'=> $request->get('album_id')];

        $validator = Validator::make($validate, $rules, $messages);

        if ($validator->fails()) {
            return Redirect::to('admin/pictures/add')->withInput()->withErrors($validator);
        }


        $random_name = str_random(8);
        $destinationPath = 'public/uploads/pictures/rallypodium/website/'.Album::find($request->get('album_id'))->type.'/'.Album::find($request->get('album_id'))->name.'/';
        $extension = $file->getClientOriginalExtension();
        $filename = $random_name.'_album_image.'.$extension;
        $uploadSuccess = $file->move($destinationPath, $filename);
        Images::create([
          'description' => $request->get('description'),
          'image' => $filename,
          'album_id'=> $request->get('album_id')
        ]);

        $uploadcount ++;

      }

      if($uploadcount == $file_count){
        Activity::log('heeft foto&#39;s in de map map "'.ucwords(str_replace('-', ' ', Album::find($request->get('album_id'))->name)).'" toegevoegd.');
        $request->session()->flash('alert-success', 'Foto&#39;s succesvol toegevoegd.');
        return Redirect::to('admin/pictures/add');
      }
    }

The problem here is, it keeps returning the error message 'U moet een afbeelding opgeven.'. It doesn't store the data in the database nor uploads the files.

This are my fields in HTML:

  • cover_image
  • album_id
  • description

Could someone help me out? I tried different ways already but I can't find the solution at all.

Kindest regards,

Robin



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

composer create-project not installing laravel5.3

I have been trying to no avail to install Laravel 5.3 but keep getting 5.2 installed. Here's what i have done.

composer create-project laravel/laravel laravel53

This should pull in the latest version of laravel which is 5.3 right? Well, i thought so but i keep getting 5.2 installed

enter image description here

Then i felt it may be a problem with composer so i ran composer self-update

composer self-update

And still get 5.2 installed when i run create-project

I'm pretty sure i am getting something wrong because i ran this same command on a friend's laptop and 5.3 got installed

I am using a mac book pro BTW

Any ideas why this is so and how it can be solved?

Much thanks



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

Show secured images with Laravel 5 and Blade

I don't want that users can access images from simply using a URL like http://ift.tt/2bPGKCQ. Therefore I store all images in the storage directory, instead of storing them in the public folder.

With a controller like this

public function show($id) {
    $img = storage_path('my_images/123.jpg');
    return response()->download($img, null, [], null);
}

the image is correctly displayed by Laravel 5, although it is stored outside from the public folder.

Great up to this point ... but I want to use Blade and surround the image with some more details. Therefore my controller looks like this

public function show($id) {
    $picture = Picture::find($id);
    $img = storage_path('my_images/123.jpg');
    return view('pictures.show', array('picture' => $picture, 'img' => $img));
}

and the view like this

<!DOCTYPE html>
<html>
    <head>
        <title>Picture </title>
    </head>
    <body>
        <h1>Picture </h1>
        <ul>
            <li>Name: </li>
            <li>Description: </li>
        </ul>
        <img src="">
    </body>
</html>

which obviously does not work, because the location of the image is not publicly accessible (which ist the intention).

What do I have to use instead of <img src=""> to make this work?



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

laravel public folder is not showing anything in browser when i go to localhost/laravel3/public path

im in real trouble, i use the composser method to setup laravel on my ubuntu system. its install completely. but when i go to localhost/laravel3/public path it shows nothing, i thing there are some permission to folder problems. i also run following commands to change permissions of laravel3 directory.

 chmod -R 777 /var/www/html/laravel3
sudo chown ateeq:ateeq /var/www/html/laravel3/

when i run ls -l command on terminal it shows folliwng results on terminal for laravel3 directory.

drwxrwsr-x 12 ateeq ateeq        4096 اگست  30 19:02 laravel3

and it shows following results when i run ls -l command from laravel3 directory or inside of this project folder.

drwxrwsrwx  6 ateeq ateeq   4096 اگست  23 18:14 app
-rwxrwxrwx  1 ateeq ateeq   1646 اگست  23 18:14 artisan
drwxrwsrwx  3 ateeq ateeq   4096 اگست  23 18:14 bootstrap
-rwxrwxrwx  1 ateeq ateeq   1283 اگست  23 18:14 composer.json
-rwxrwxrwx  1 ateeq ateeq 123589 اگست  30 19:02 composer.lock
drwxrwsrwx  2 ateeq ateeq   4096 اگست  23 18:14 config
drwxrwsrwx  5 ateeq ateeq   4096 اگست  23 18:14 database
-rwxrwxrwx  1 ateeq ateeq    556 اگست  23 18:14 gulpfile.js
-rwxrwxrwx  1 ateeq ateeq    400 اگست  23 18:14 package.json
-rwxrwxrwx  1 ateeq ateeq    930 اگست  23 18:14 phpunit.xml
drwxrwsr-x  4 ateeq ateeq   4096 اگست  23 18:14 public
-rwxrwxrwx  1 ateeq ateeq   1918 اگست  23 18:14 readme.md
drwxrwsrwx  5 ateeq ateeq   4096 اگست  23 18:14 resources
drwxrwsrwx  2 ateeq ateeq   4096 اگست  23 18:14 routes
-rwxrwxrwx  1 ateeq ateeq    563 اگست  23 18:14 server.php
drwxrwsrwx  5 ateeq ateeq   4096 اگست  23 18:14 storage
drwxrwsrwx  2 ateeq ateeq   4096 اگست  23 18:14 tests
drwxrwsrwx 31 ateeq ateeq   4096 اگست  30 19:03 vendor

when i check owner of the laravel folder it show "me". and also for sub-folders inside laravel3 folders



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

Laravel 5 validate error message not showing

Sorry, i am a beginner for laravel 5, I try to validate register form but it not showing error message. Any idea why errors are not displaying. Please help.

thank you so much.

Here are my code

View

                        <form role="form" method="post" action="">
                      <div class="form-group">
                        <label for="name">Full Name</label>
                        <input  type="text" name="fullname" class="form-control" id="fullname" value="" placeholder="Enter your fullname">
                        @if ($errors->has('fullname'))
                            <span class="help-block"></span>
                        @endif
                      </div>
                        <div class="form-group">
                            <label for="email" class="control-label">Your email address</label>
                            <input type="text" name="email" class="form-control" id="email" value="" placeholder="Enter your email">
                            @if ($errors->has('email'))
                                <span class="help-block"></span>
                            @endif
                        </div>
                        <div class="form-group">
                            <label for="password" class="control-label">Choose a password</label>
                            <input type="password" name="password" class="form-control" id="password" placeholder="Enter your password">
                            @if ($errors->has('password'))
                                <span class="help-block"></span>
                            @endif
                        </div>
                        <div class="form-group">
                            <label class="control-label">Confirm Password</label>
                            <input type="password" class="form-control" name="password_confirmation" placeholder="Re-Enter your password">

                            @if ($errors->has('password_confirmation'))
                                <span class="help-block">
                                    <strong></strong>
                                </span>
                            @endif
                        </div>
                        <input type="hidden" name="activated" value="0">
                        <input type="hidden" name="_token" value="">
                        <button type="submit" class="btn btn-warning btn-sm">Submit</button>
                        <button type="reset" class="btn btn-default btn-sm">Reset</button>
                    </form>

Controller

public function postRegister(Request $request) {

    $this->validate($request, [
        'email' => 'required|email|max:255',
        'password'  =>'required|alphaNum|Between:4,8|Confirmed',
        'password_confirmation'=>'required|alphaNum|Between:4,8',
        'fullname' => 'required|max:255',
        'activated' => 'required',
    ]);

    Admin::create([
        'email' => $request->input('email'),
        'password' => $request->input('password'),
        'fullname' => $request->input('fullname'),
        'activated' => $request->input('activated')
    ]);

    return redirect('backoffice/register')->with('info', 'register successfully!');

}

Route

Route::get('backoffice/register', 'AdminAuthController@getRegister');
Route::post('/backoffice/register', 'AdminAuthController@postRegister');



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

Laravel routing with virtual sub-domain name

I am making one application where some routes should act like they are routing from sub domain.

NB : I don't want to create sub domains. Everything will work from the controllers and routes.

This is the url

http://ift.tt/2bT2CfL

This is the route

Route::group(['domain' => '{site}.myapp.com'], function () {
   Route::get('/{site}/{page}', 'page@site');

});

I am trying to make the url look like

http://ift.tt/2bP3m8d

Can anyone help me how to achieve this one ?



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

Laravel 5: Migration-Route - Artisan::call('migrate', array('--force' => true)) stops

I have an migration-route in my application, the current output is:

init migrate:install...done migrate:install
init with tables migrations...

Now it stops. But the output should continue. Heres the route:

Route::get('/migrate', function () {
    try {
        try {
            echo '<br>init migrate:install...';
            Artisan::call('migrate:install');
            echo 'done migrate:install';
        } catch (Exception $e) {
            echo 'allready installed';
        }

        echo '<br>init with tables migrations...';
        Artisan::call('migrate', array('--force' => true)); // here it stops via browser
        echo 'done with migrations';

        echo '<br>clear view cache...';
        $cachedViewsDirectory = app('path.storage').'/framework/views/';

        if ($handle = opendir($cachedViewsDirectory)) {
            while (false !== ($entry = readdir($handle))) {
                if(strstr($entry, '.')) continue;

                @unlink($cachedViewsDirectory . $entry);
            }

            closedir($handle);
        }
        echo 'all view cache cleared';

        return redirect()->route('backend::dashboard');
    } catch (Exception $e) {
        Response::make($e->getMessage(), 500);
    }
});

While accessing the Shell and run the migration it will work:

-bash-4.2$ /opt/plesk/php/5.6/bin/php artisan migrate
**************************************
*     Application In Production!     *
**************************************

 Do you really wish to run this command? (yes/no) [no]:
 > yes

Migrated: 2016_08_23_194102_import_old_data
Migrated: 2016_08_25_080129_import_old_adresses
Migrated: 2016_08_25_080801_import_oldname_to_accountholder

Why it doesn't work from route?



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

how to Prioritize queued events?

I am working in laravel 5.0

I am using database as queue driver. I have created 2 events A and B. I want event B to always execute first. Even if Event B is inserted in Jobs table after Event A it should execute first.

Both of my events consists of

implements ShouldBeQueued

and

 use InteractsWithQueue;

So both events are going into jobs table and i have supervisor(process manager) to handle them..

It is working fine so far, Just that i want to give high priority to Event B over Event A.

Any help would be appreciated..



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

composer problems with installing Laravel 5.2

I got the following error when run

composer create-project laravel/laravel=5.2 job --prefer-dist

however when I don't specifiy the version of laravel it works fine,

I tried to do composer clearcache but It does not fix the error :(

here is the error:

> php -r "copy('.env.example', '.env');"
> php artisan clear-compiled

Warning: require(C:\xampp\htdocs\laravel\jobsapi\job\bootstrap/../vendor/autoload.php): failed to open stream: No such file or directory in C:\xampp\htdocs\laravel\jobsapi\job\boo
tstrap\autoload.php on line 17

Fatal error: require(): Failed opening required 'C:\xampp\htdocs\laravel\jobsapi\job\bootstrap/../vendor/autoload.php' (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\lara
vel\jobsapi\job\bootstrap\autoload.php on line 17
Script php artisan clear-compiled handling the pre-update-cmd event returned with error code 255

in spite of the error Laravel 5.2 is partially installed by the vendor folder is missing



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

bash: homestead: command not found(homestead init) not working

I've already installed composer global require "laravel/homestead=~2.0" but still "homestead init" is not working. or any commands.

I've tried to work with but still i can't fix it.

can someone help me working with this?? please!



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

lundi 29 août 2016

Laravel 5: how to decode json returned from ajax call

I am working on a shopping cart application. when the user clicks the add to cart button, I want the ajax call to my controller function to return two values: totalPrice and totalQty which are to be displayed on the page. I have been able to return the values in as json: {"totalPrice":100,"totalQty":1}. Now how do i extract the totalPrice and totalQty to display on different parts of the page. Thanks.

Here is my code:

<a data-id="" class="btn btn-success addToCart" >Add to cart</a>

Here is code for my ajax:

    <script type="text/javascript">
    $(function(){
        $.ajaxSetup({
            headers: {
                'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
            }
        });

        $('.addToCart').click(function(){
            var id = $(this).data('id');

            $.ajax({
                url  : "",
                type : "POST",
                data : {
                    'id' : id,
                    "_token": ""
                },
                success:function(data){
                   alert(data); // returns {"totalPrice":100,"totalQty":1}
                   // how do I decode and display data returned here?
                }
            });
        });

    });
</script>

Here is my controller method:

public function addToCart(Request $request){
    $post = $request->all();
    $id = $post['id'];
    $product = Product::find($id);

    //some code is excluded to simplify this function

    $total_price = 100;
    $total_qty = 1;
    $vals = array('totalPrice' => $total_price,'totalQty' => $total_qty);
    $vals = json_encode($vals);
    echo $vals;
    exit();

}

This is where json values returned are supposed to be displayed:

<a href="">
Cart - <span class="cart-amunt">//display amount here</span> 
<span class="product-count"> //display totalQty here </span>
</a>



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

Laravel 5.3 pre-built authentication

I'm trying to implement authentication for my application using pre-built authentication provide by Laravel . Used command

php artisan make:auth

The proplem is when i'm trying to login, i get "These credentials do not match our records." but the register work fine .

Note

The user table DDL create syntax .

CREATE TABLE users (
  ID int(11) NOT NULL AUTO_INCREMENT,
  NAME VARCHAR(40) NOT NULL,
  PASSWORD CHAR(60) NOT NULL,
  EMAIL VARCHAR(255) NOT NULL,
  REMEMBER_TOKEN VARCHAR(255) NULL,
  PRIMARY KEY  ('ID')
); 



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

Laravel - JWT Auth The token could not be parsed from the request

I have added following code in my middleware for user authentication with JWT Auth, which works fine for all the routes handled by the middleware.

public function handle($request, Closure $next)
{
    if ($request->has('token')) {
        try {
            $this->auth = JWTAuth::parseToken()->authenticate();
            return $next($request);
        } catch (JWTException $e) {
            return redirect()->guest('user/login');
        }
    }
}

But for one route with Post Method where the token is getting passed properly but still I am getting JWTException - The token could not be parsed from the request, on the same route when I tried

public function handle($request, Closure $next)
{
    if ($request->has('token')) {
        try {
            dd($request->input('token'));
            $this->auth = JWTAuth::parseToken()->authenticate();
            return $next($request);
        } catch (JWTException $e) {
            return redirect()->guest('user/login');
        }
    }
}

output:

"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9iaXNzIjoiaHR0cDpcL1wvbG9jYWxob3N0OjgwMDFcL2F1dGhcL2xvZ2luIiwiaWF0IjoxNDcyNTI4NDU0LCJleHAiOjE0NzI1MzIwNTQsIm5iZiI6MTQ3MjUyODQ1NCwianRpIjoiM2E0M2ExYTZlNmM5NjUxZDgxYjZhNDcxMzkxODJlYjAifQ.CH8ES2ADTCrVWeIO8uU31bGDnH7h-ZVTWxrdXraLw8s"

I am able to see the Valid Token which I am using to access another routes and which is working flawlessly for all other routes.

Thanks in advance!!!



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

does jquery-ias work with laravel

I cannot get jquery-ias with Laravel 5. I am having difficulties debugging it. I was wondering if anyone got jquery-ias to work with Laravel 5 and if you could share some sample code.

Thanks



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

Laravel 5. DB::select working principles

Here is the raw SQL query:

    $best_price = DB::select('select id,product_id, shop_name, product_name, brand, weight_volume, min(price)

    FROM (
            select
    p.id, p.product_id, p.shop_id, s.shop_name, pr.product_name, pr.brand, coalesce(pr.weight, pr.volume) weight_volume, p.price

    from prices p
    inner join (
            select p1.id price_id,p1.product_id id, max(p1.created_at) maxed_date

    from prices p1

    where product_id= ?

    group by p1.id, p1.product_id, p1.shop_id) grouped on grouped.maxed_date=p.created_at and grouped.price_id=p.id
    join products pr on pr.id=p.product_id
    join shop_names s on s.id=p.shop_id

    group by p.id, p.product_id, p.shop_id) grouped

    GROUP BY product_id,shop_name', [$request->product]);

In DBeaver I get result of one line with min(price) of "Metro C&C".

But if I do dd($best_price) I get the following result:

array:2 [▼
  0 => {#158 ▼
    +"id": 46
    +"product_id": 69
    +"shop_name": "Metro C&C"
    +"product_name": "Cream"
    +"brand": ""Tastyland""
    +"weight_volume": 0.22
    +"min(price)": 300.0
  }
  1 => {#160 ▼
    +"id": 47
    +"product_id": 69
    +"shop_name": "Klopshop"
    +"product_name": "Cream"
    +"brand": ""Tastyland""
    +"weight_volume": 0.22
    +"min(price)": 300.0
  }
]

And if I do

foreach($best_price as $best_price_id) {
            return $best_price_id->shop_name;
        };

I received the following result "Metro C&C".

I have the following questions:

  1. How does Laravel understand, that there are two results with minimum price of 300(actually this is the result that I expect) while DBeaver provides only one? How should I change the SQL query to get result of 2 rows?

  2. Why does foreach return only the first row?



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

Dynamically adding data to div from model on dropdown select

I've been searching for quite a while and can't find a solid answer for this. I'm using Laravel 5.3 as well as Laravel Collective for the forms and Chosen to manipulate my select boxes.

Basically I have a select dropdown, which has values in it that are pulled from the database. When I select a value, I wan't to populate each empty 'panel' on the page with the relevant model data for the selected item.

So for example when I select 'admin' I want to look in the 'roles' table and display 'description' and 'display_name' associated with the selected value. Furthermore I want to get the associated permissions for that entry and display them as well.

Here is my form:

                            <div class="form-group">
                                <script type="text/javascript">
                                    $(document).ready(function() {
                                        $(".role").chosen()
                                    });
                                </script>
                                {!! Form::label('Role') !!}
                                <div class="input-group">
                                    <div class="input-group-addon"><i class="fa fa-user-plus" aria-hidden="true"></i></div>
                                    {!! Form::select('role', $roles, null, ['id' => 'role', 'class' => 'select-width-100 form-control role']) !!}
                                </div>
                            </div>
                            {!! Form::label('Display Name') !!}
                            <div class="panel panel-default">
                                <div class="panel-body" name="d_name" id="d_name">

                                </div>
                            </div>
                            {!! Form::label('Description') !!}
                            <div class="panel panel-default">
                                <div class="panel-body" name="description" id="description">

                                </div>
                            </div>

                            <div class="input-group">
                              <span class="input-group-btn">
                                <button class="btn btn-danger" type="submit" name="update">Update</button>
                              </span>
                            </div>

I know there is a way to fire ajax and receive it with a 'route::get' but I have no idea how to do this or where to start. My Jquery skills are severely lacking.

Any help would be greatly appreciated.



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

Laravel 5. Retrieve data from DB::select

Code:

        $best_price = DB::select('Some SQL statement');

        foreach($best_price as $best_price_id) {
            $best_price_id->id;
        };


        $product->best_price_id = $best_price_id;

        return $product->best_price_id;

Result:

The Response content must be a string or object implementing __toString(), "object" given.

Definately I am retrieving information from the DB incorrectly. Please suggest better option.



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

Please assist with complex mysql query converting for use in Laravel 5

Here is my query.. I have tried several different ways to get the proper result while formatting for laravel 5, if anyone can assist with the proper format I would greatly appreciate it

  SELECT z.id, z.address, z.city, z.state, z.zip, 
    z.latitude, z.longitude, 
      (p.distance_unit 
        * DEGREES(ACOS(COS(RADIANS(p.latpoint)) 
        * COS(RADIANS(z.latitude)) 
        * COS(RADIANS(p.longpoint) - RADIANS(z.longitude)) 
        + SIN(RADIANS(p.latpoint)) 
        * SIN(RADIANS(z.latitude))))) AS distance 
  FROM locations AS z 
  JOIN ( 
    SELECT ? AS latpoint, 
           ? AS longpoint, 
           ? AS radius, 
           ? AS distance_unit 
    ) AS p 
  WHERE z.latitude 
    BETWEEN p.latpoint  - (p.radius / p.distance_unit) 
    AND     p.latpoint  + (p.radius / p.distance_unit) 
  AND   z.longitude 
    BETWEEN p.longpoint - (p.radius / (p.distance_unit * COS(RADIANS(p.latpoint)))) 
    AND     p.longpoint + (p.radius / (p.distance_unit * COS(RADIANS(p.latpoint)))) 
  ORDER BY distance 
  LIMIT ?

my variables are in order:

$latpoint
$longpoint
$radius
$distance_units
$limit



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

How do we concatenate using blade template engine Laravel

I am new to Laravel and don't know if it is possible at all to concatenate a string to a blade variable.

I want to display the name of the author with the ~ sign concatenated to the author's name from the left. Here is my code.

<div class="author">~</div>

What I want is if the author is set, it should be displayed with the ~. How do I concatenate this? Thanks for any help



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

how to redirect different pages in Laravel 5.2

I need redirect user pages according to status of the user. I wrote a method in My Controller in Laravel 5.2 status 1 is working but when I add else and else if function it generate following errror.

FatalErrorException in ProjectCollaboratorsController.php line 219: syntax error, unexpected 'return' (T_RETURN)

My controller method is folllowing

public function show($id){
 if (Permission::where('status', 1)->where('project_id', $id)->exists()){

    $project = Project::find($id);
    $tasks = $this->getTasks($id);
    $files = $this->getFiles($id);
    $comments = $this->getComments($id);
    $collaborators = $this->getCollaborators($id);
    $permissions = $this->getPermissions($id);



    return view('collaborators.show');
    }
else{

    (Permission::where('status', 2)->where('project_id', $id)->exists()) 
         return view('collaborators.manager');

}

else if {

(Permission::where('status', 3)->where('project_id', $id)->exists()) 
         return view('collaborators.user');
}
    }



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

Laravel5 whereRaw not working to parameterize column name

I'm trying to build the column sent_storename with my whereRaw statement. But when I try to concatenate the values, the query doesn't work. When I fix the column it works. How can I do this?

$query = $this->model->getQuery()->where('products.environment_hash', $hash )->whereRaw('products.deleted_at is null');
$query->select('sku_config','name', 'stock_quantity', 'color', 'size', 'special_price', DB::raw('(special_price/default_price-1)*100 as profit_mark'));
$query->leftJoin('ads', 'ads.product_id', '=', 'products.id');
$query->whereRaw("products.sent_? = 0", array('storename'));



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

My Jobs are getting inserted into the table. But they aren't executing. What should I Do?

"php artisan queue:work --daemon"(Supervisor) commands are already running in the background. Jobs are also getting inserted into the job table. But They are not executing..???



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

Laravel5: Why my model "Media" require table named "media" instead of "medias"?

From the doc of laravel, it claims:

Now, let's look at an example Flight model, which we will use to retrieve and store information from our flights database table

So I wrote:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Media extends Model
{
    //
}

But when I run my application, it gives that error:

QueryException in Connection.php line 729:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'myapp.media' doesn't exist (SQL: select * from `media`)

It requires a table named media instead of medias as document said. So why that errors happened? Do I accidentally open option flag which changed the default name mapping from model to table or something similar?

Any suggestion will be appreciated.


Environment:

  • Laravel Framework version 5.2.43
  • PHP 7.0.8-2+deb.sury.org~xenial+1


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

Laravel 5.1 one form two submit buttons

I am using Laravel 5.1, and I would like to make a form with two submit buttons - Save and Save draft.

But when I post my form I have all the fields except the submit value.

I read that Laravel won't put the submit button value in the POST when the form was sent via ajax, so could you please help me how to do this?

Here are some code how it looks like now:

{!! Form::open(['url' => 'offer/create', 'method' => 'post', 'id' => 'offer-create']) !!}

....
here are my fields
....

{!! Form::submit( 'Save', ['class' => 'btn btn-default', 'name' => 'save']) !!}

{!! Form::submit( 'Save draft', ['class' => 'btn btn-default', 'name' => 'save-draft']) !!}

In my routes.php I have:

Route::controller('offer', 'OfferController');

Thanks in advance



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

Date Not Inserted In Database Using Angular js And Laravel

Here i am using angular js iand trying to insert attendence from form attendance-form.blade.php in table attendance on button click. Now the problem is that as i click on button create there is no insertion of data in table attendance.Below is the code i done

In attendance-form.blade.php

<div ui-view="attendanceForm">
<div class="mdl-grid demo-content" ng-controller="AttendanceFormController">
    <div class="demo-charts mdl-color--white mdl-shadow--2dp mdl-cell mdl-cell--12-col mdl-grid">
        <form>
            <div class="form-group label-static is-empty">
                <h3>Create Attendance</h3>
                <div class="form-group label-static is-empty">
                    <input type="text" name="user_id" class="attendance-form form-control"
                           id="i2" placeholder="user_id" ng-model="attendance.user_id">
                </div>
                <div class="form-group label-static is-empty">
                    <input type="text" name="in_or_out" class="attendance-form form-control"
                           id="i2" placeholder="in_or_out" ng-model="attendance.in_or_out">
                </div>
                <div class="form-group label-static is-empty">
                    <input type="text" name="comment" class="attendance-form form-control"
                           id="i2" placeholder="comment" ng-model="attendance.comment">
                </div>
                <div class="attendance-form form-group label-static is-empty ripple-container">
                    <input type="button" value="Create" class="btn btn-raised btn-primary" ng-click="abc()">
                </div>

            </div>
        </form>
    </div>
</div>

In AttendanceController.js

app.controller('AttendanceFormController', function ($scope, AttendanceService) {
$scope.attendance = {};
$scope.attendance.user_id
$scope.attendance.in_or_out;
$scope.attendance.comment;

$scope.loadAttendance = function () {
    $scope.user = AttendanceService.get({id:$scope.params.id});
}

$scope.abc = function () {

                                attendance = {user_id:$scope.attendance.user_id,
                                in_or_out:$scope.attendance.in_or_out,
                                comment:$scope.attendance.comment,

    }

    AttendanceService.post(attendance).then(function(response){
        alert('Attendance successfully added in the system.'+'\n'+'Check console.log for response.');
        console.log(response.data);
    });

}

});

In AttendanceFactory.js

app.factory('AttendanceRESTClient', function ($resource) {
return $resource('api/attendance/:id', {id: '@id'}, {
    'query': {method: "POST", isArray: false }
});

})

In AttendanceService.js

var AttendanceService = app.service('AttendanceService', function (AttendanceRESTClient) {
return {
    get: function(id) {
        return AttendanceRESTClient.get({id:id.id}).$promise;
    },

    getEdit:function(id){
        return AttendanceRESTClient.getEdit({id:id.id})
    },

    post: function(attendance){
        return AttendanceRESTClient.save(attendance).$promise;
    },

    all: function(){
        return AttendanceRESTClient.query().$promise;
    },

    edit: function(attendance){
        return AttendanceRESTClient.edit(attendance)
    }
}

})



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

How to enableQueryLog Database Laravel after app start.

I want get Query in controller laravel but i must DB::enableQueryLog() in function i using DB::getQueryLog() . I want DB::enableQueryLog() when app start. To be DB::getQueryLog() without DB::enableQueryLog() in controller.

Please help! Thank so much



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

Laravel 5 group by relationship's column

I am using Laravel 5.2. I have 2 models : Vehicle and Brand

Eloquent Relationships are as follows:

Vehicle belongsTo Brand

Brand hasMany Vehicles

I wanted the count of vehicles in each Brand with Brand name after applying a set of filters to the vehicles list.

My code:

        $result = Vehicle::ApplyFilters($conditions)  // this is a scope applied initially
                ->with(['brand' => function($query) {
                    return $query->groupBy('brand_name');
                }])->get();

Unfortunately not getting desired result. It is listing the vehicles and not grouped by brand.

I am a newbie. Any idea to make it work?



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

Append form action with input variable

I have a form whose action is

<form action="/food/vegetable" method="POST" >

My controller method takes vegetable name as parameter

I would like to append the input vegetable name to the action. for example

<form action="/food/vegetable/{vegetableName}" method="POST" >

Is it possible to do this ? or is there a better way ? Please guide.



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

dimanche 28 août 2016

Laravel localization problems 5.2+

This is my middleware.

class BeforeMiddleware{

public function handle($request, Closure $next)
{
    // Perform action

    App:setLocale(LC_ALL,Session::get('locale'));

    return $next($request);
}

If i don't place LC_ALL as first parameter in setLocale i get this error.

"setlocale() expects at least 2 parameters, 1 given"

If i put LC_ALL as the first parameter localization doesn't change. Version of laravel is 5.2+



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

How to validate AM/PM on Laravel5?

I'm looking for validate 12 hours. A.M. 00:00 ~ 11:59 and P.M. 12:00 ~ 23:59.

Input value come like this.

<input type="text" name="am" value="00:00" />
<input type="text" name="am" value="11:59" />

<input type="text" name="pm" value="12:00" />
<input type="text" name="pm" value="23:59" />

So I made validate like this.

'am' => ['http://regex:/^(1[01]|0[0-9]):[0-5][0-9]$/'],
'pm' => ['http://regex:/^(2[0-3]|1[2-9]):[0-5][0-9]$/'],

Does Laravel have any good validation without regex? (like after:tomorrow) I don't wanna use regex that make code difficult to reading comprehension. Any Ideas?



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

make table with foreach and for work in same time

here I would like to make a table where there number of rows will automatically be made in accordance with the data in $ kosts-> stock_room. and then there is also I want to make the data directly arranged with the data I have on the table residents by room number, so if i have data in table 'residents' with room number 10 its will fill the table with row 10.

here my code :

<table class="table table-hover table-striped">
        <tr>
            <th width="10%">Action</th>
            <th>Room</th>
            <th>Kost</th>
            <th>Name</th>
            <th>Due Date</th>
        </tr>        
        <tr>
            @foreach($posts as $row)
            @for($i=1;$i<=$kosts->stock_room;$i++) 
            <tr>
            <td>                
            <a title='Edit Data' class='btn btn-xs btn-warning' href=''><i class='fa fa-pencil'></i></a>
            <a title='Delete Data' class='btn btn-xs btn-danger' href='' onclick="return confirm('sure to delete ?')"><i class='fa fa-trash'></i></a>                      
            </td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            </tr>   
            @endfor
            @endforeach
        </tr>
    </table>

have someone can help me, to make my code can work exactly like I want?

and iam sorry for my bad english



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

Laravel 5.3 can't login with Auth::attempt

i Have a fucntion

if (Auth::attempt(['username' => 'trannghj', 'password' => 'trannghj2281996'], true, true)) {
        dd(Auth::check());
    } else
        dd('Not login');

this return true but dd(Auth::check()); this return false; I use laravel 5.3 Please help me. Thank you!



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

Laravel 5: using bcrypt on same string gives different values

I am using Laravel's bcrypt function for hashing passwords. When I do,

bcrypt('secret')

I get

=> "$2y$10$mnPgYt2xm9pxb/c2I.SH.uuhgrOj4WajDQTJYssUbTjmPOcgQybcu"

But if I run it again, I get

=> "$2y$10$J8h.Xmf6muivJ4bDweUlcu/BaNzI2wlBiAcop30PbPoKa0kDaf9xi"

and so on...

So, won't the password matching process fail if I get different values every time?



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

laravel 5.3 new Auth::routes()

Recently I start to use laravel 5.3 to write a blog, but I have a question after run php artisan make:auth

when I run this, it will generate routes in my web.php

this is the code in it:

Auth::routes();

Route::get('/home', 'HomeController@index');

Then I run php artisan route:list, I find lots of actions, like LoginController@login...

But I didn't find these actions in my App\Http\Controllers\Auth, where are these?

And also what is the Auth::routes() stand for, I can't find the routes about Auth.

I need someone help, thank you to answer my question



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

Laravel: Uploadify request to uploadify.swf issue

I am trying to add uploadify to Laravel 5. When I load my page, it sends a request to URL myBaseUrl/controller/uploadify.swf to which I get response of method not allowed Exception. I am not sure what to do and how to proceed.

Routes

Route::post('/products/upload','productsController@upload');

Uploadify call

<script type="text/javascript">
    <?php $timestamp = time();?>
    $(function() {
        $('#file_upload').uploadify({
            'formData'     : {
                'timestamp' : '<?php echo $timestamp;?>',
                '_token': $('#_token').val()
            },
            'preventCaching' : false,
            'swf'      : 'uploadify.swf',
            'uploader' : 'BaseUrl/products/upload'
        });
    });
</script>

Please guide. Thanks



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

error while trying to run artisan command with Artisan Facade

here's the code

Route::get('run-cmd', function() {
    Artisan::call('make:controller HelloController');
});

and I wonder I'm getting this error...

InvalidArgumentException in Application.php line 549:
Command "make:controller HelloController" is not defined.
Did you mean one of these?
make:migration
make:controller
make:middleware
make:request
make:provider
make:console
make:event
make:model
make:command

what's wrong?



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

EAV is 'bad', so I need hundreds of tables?

I'm building a product catalog with hundreds of different product types. These product types have a lot of different attributes. Some are shared, but most are specific for the product type.

My initial thought was to go with an EAV-type structure, but I understand why that might be a bad choice. Especially since I want my database to enforce correctness and consistency, which is going to be a mess with EAV.

The alternative in my case would be class table inheritance. I'm a bit worried about the maintainability though... how am I going to maintain hundreds of migrations and models? Is that really a desirable situation? I understand the benefits, but isn't maintainability a huge downside?



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

Call to undefined method Illuminate\Auth\TokenGuard::login()

I try to register a new user to my app using only JSON and api guard with token driver. I got this strange error :

FatalThrowableError in RegistersUsers.php line 32:
Call to undefined method Illuminate\Auth\TokenGuard::login()
in RegistersUsers.php line 32
at RegisterController->register(object(Request))
at call_user_func_array(array(object(RegisterController), 'register'), array(object(Request))) in Controller.php line 55
at Controller->callAction('register', array(object(Request))) in ControllerDispatcher.php line 44
at ControllerDispatcher->dispatch(object(Route), object(RegisterController), 'register') in Route.php line 189
at Route->runController() in Route.php line 144
at Route->run(object(Request)) in Router.php line 642
at Router->Illuminate\Routing\{closure}(object(Request)) in Pipeline.php line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in RedirectIfAuthenticated.php line 24
at RedirectIfAuthenticated->handle(object(Request), object(Closure)) in Pipeline.php line 137
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in Pipeline.php line 104
at Pipeline->then(object(Closure)) in Router.php line 644
at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 618
at Router->dispatchToRoute(object(Request)) in Router.php line 596
at Router->dispatch(object(Request)) in Kernel.php line 267
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request)) in Pipeline.php line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in CheckForMaintenanceMode.php line 46
at CheckForMaintenanceMode->handle(object(Request), object(Closure)) in Pipeline.php line 137
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in Pipeline.php line 104
at Pipeline->then(object(Closure)) in Kernel.php line 149
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 116
at Kernel->handle(object(Request)) in index.php line 53



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

Eloquent ORM returns null using with() eager load

When using Eloquent's with() the eager loaded data sometimes becomes null. In my case, I have three tables, Users, Blogposts and Categories. The blogposts table has two foreign keys, called author and category. The query performed is given by

return Blogpost::with(['author', 'category'])->get();

The response is, well, odd. Note that author becomes null from id: 3 and category from id: 4.

In reality both the ids 1, 3 have the same author (superuser) as do the ids 2, 4 (steve). Also id 1, 4 have the same category (web dev).

It seems as if a/an category/author is already retrived and bounded to a blogpost the past categories/authors becomes null.

[
  {
    id: 4,
    author: null,
    image_name: "banner1.png",
    category: null,
    intro: "Hello World!",
  },

  {
    id: 3,
    author: null,
    image_name: "banner1.png",
    category: {
        id: 3,
        name: "big data",
    },
    intro: "Hello World!",
  },

  {
    id: 2,
    author: {
        id: 2,
        email: "foo@foo.foo",
        fullname: "foo foo",
        is_admin: false,
    },
    image_name: "banner1.png",
    category: {
        id: 2,
        name: "science",
    },
    intro: "Hello World!",
  },

  {
    id: 1,
    author: {
        id: 1,
        email: "superuser@superuser.com",
        fullname: "superuser superuser",
        is_admin: true,
    },
    image_name: "banner1.png",
    category: {
        id: 1,
        name: "web dev",
    },
    intro: "Hello World!",
  }
]

Finally here are the relations defined in the models

// User model
public function blogposts() {
    return $this->hasMany('App\Blogpost', 'id');
}

// Blogpost model
public function author() {
  return $this->belongsTo('App\User', 'id');
}

public function category() {
  return $this->belongsTo('App\Category', 'id');
}

// Category model
public function blogposts() {
  return $this->hasMany('App\Blogpost', 'id');
}

Is there any explanation to this?



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

How can I get sessions created earlier in laravel

I need to sort my sessions by created earlier in Laravel, And I don't use session table. To do this you have any suggestions? I don't know by filename or any ? thanks all and sorry for my terrible English grammer.



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

Convert Mysql Query to Laravel 5 Eloquent

I am using Laravel 5.1 in my application. My MySQL Query is

$result = DB::select(DB::raw("Select * from "
            . "(Select u.* from "
            . "( "
            . "SELECT u2.id as user_id, u2.fname as fname, u2.lname as lname, u2.uname as uname, u2.email as email, u2.address as address, u2.city_id as city_id, u2.website as website FROM users u1, users u2 where u1.city_id = u2.city_id && u1.id = '$this->current_user_id' ) 
                u left join follows f on u.user_id = f.following_id where f.following_id is null 
                UNION
                Select uu.id as user_id, uu.fname as fname, uu.lname as lname, uu.uname as uname, uu.email as email, uu.address as address, uu.city_id as city_id, uu.website as website from users uu where uu.id in (Select u.user_id from (SELECT user_id FROM reviews group by user_id order by count(user_id) desc5
                ) u left join follows f on u.user_id=f.following_id where f.following_id is null
                )
                ) 
                T LIMIT 5"
    ));

How Can I convert it in Laravel Eloquent?



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

Laravel 5.2 - Sweet Alert confirmation box

I have Categories listed in a view. A delete category button is also there in the view which does work and deletes the category when clicked.

What I want to do is before deleting a category, a sweet alert dialog to pop up and ask for confirmation. If confirmed, it should go to the defined route and delete the category.

The delete link is defined like this:

<a id="delete-btn" href="" class="btn btn-danger">Delete</a>

and the script is defined like this:

<script> 
    $(document).on('click', '#delete-btn', function(e) {
        e.preventDefault();
        var link = $(this);
        swal({
            title: "Confirm Delete",
            text: "Are you sure to delete this category?",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "Yes, delete it!",
            closeOnConfirm: true
         },
         function(isConfirm){
             if(isConfirm){
                window.location = link.attr('href');
             }
             else{
                swal("cancelled","Category deletion Cancelled", "error");
             }
         });
    });
</script>

However, when I click the delete button it deletes the category, but the sweet alert message doesn't show up.

The route is defined as following:

Route::get('/categories/destroy/{category}', [
    'uses' => 'CategoriesController@destroy',
    'as' => 'admin.categories.destroy',
]);

and the controller function is defined as:

public function destroy(Category $category) 
{

    $category->delete();

    //this alert is working fine. however, the confirmation alert should appear 
    //before this one, which doesn't
    Alert::success('Category deleted successfully', 'Success')->persistent("Close");

    return redirect()->back();
}

Any help would be appreciated. Thanks.



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

samedi 27 août 2016

How injecting a array in my view with laravel 5 using a facade and the App:make method in the view

I created a facade that works well, a using service container :

My class :

namespace App\Classes;

class Administration {

  public function message_success()
{
   $message = "success";

  return $message;

  }

}

My view :

Résultat Ok

But when I want to work with a array, I can not retrieve a value in my view with App::make.

My class :

namespace App\Classes;

class Administration {

public function message_test($message, array $type = array())
{

  $type = ['message1' => 'valeur1', 'message2' => 'valeur2'];

  return $message;

  }

}

How to build the syntax in my view?



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

POST controller for all routes in Laravel 5

I have callback button in header of my webpage, so user can send me message from every page. How to make route for this? Something like that:

Route::post('{*}', 'PostController@callback');



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

Return result after the event is fired in Laravel 5.2

My original code is below

/*
   Create the Role
*/  

$result = (new RoleDb())->Create($obj);

if($result["Success"]) {

    /*
    | Get all Modules 
    */

    $Permissions = $this->Module->All($obj->RoleID);
    $list = [];

    /*
    | Prepare the list that will be assigned to Newly created role.
    */

    foreach($Permissions["Data"] as $Permission) {
        $RolePermissionOM = new RolePermissionOM();
        $RolePermissionOM->PermissionID             = $Permission->PermissionID;
        $RolePermissionOM->IsActive                 = $Permission->DefaultPermission;
        $RolePermissionOM->RoleID                   = $result["Data"];
        array_push($list, $RolePermissionOM);
    }

    /*
    | Create default permissions for above created role.
    */

    return $this->RolePermission->CreateDefaultPermissions($list, $result["Data"]);
}

Now, in my application, there are 3 more points where role is being created and instead of code duplication, I though to convert this code into event. SO whenever a role is being created, an Event is being fired to create the permission records for that role.I wrote the below code.

Event::fire(new RoleCreationEvent($result));
// `$result` contains the newly created RoleID.

Question : In my original code, I was able to get the result to check if the permissions are saved correctly or not. How will I do that in case of firing the Event ?



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

Angular2 Can't see my custom headers attached

I am trying to attach a custom Authorization header to my get requests in my angular2 app.

Here's my code:

private headers : Headers;
  constructor (private http: Http)
  {
    this.headers = new Headers();
    //this.headers.append('Content-Type', 'application/json');
    let jwt = localStorage.getItem('id_token');
    if(jwt)
      this.headers.append('Authorization', 'Bearer ' + jwt);
  }

  private journalsUrl = Config.API_URL + 'journal';  // URL to web API

  getJournals (): Observable<Journal[]>
  {
    return this.http.get(this.journalsUrl, { headers: this.headers })
                    .map(this.extractData)
                    .catch(this.handleError);
  }

I made sure that my laravel 5 with barryvdh/laravel-cors server allowed pretty much everything related to headers:

'supportsCredentials' => false,
'allowedOrigins' => ['*'],
'allowedHeaders' => ['*'],
'allowedMethods' => ['*'],
'exposedHeaders' => ['Authorization'],
'maxAge' => 0,
'hosts' => [],

As I debug when I look at the networks tab in google chrome looking at the headers of that particular request that fails I see: General:

Request URL:http://ift.tt/2bGZPHq
Request Method:OPTIONS
Status Code:401 Unauthorized
Remote Address:127.0.0.1:80
Response Headers

Request Headers:

Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8,ar;q=0.6
Access-Control-Request-Headers:authorization
Access-Control-Request-Method:GET
Connection:keep-alive
Host:api.ketabuk.dev
Origin:http://localhost:3000
Referer:http://localhost:3000/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36

Notice that: Access-Control-Request-Headers:authorization. But notice also that the Authorization field itself is not there.

What am I doing wrong?



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