Tuesday, February 28, 2017

Laravel syntax error, unexpected 'routes' (T_STRING)

I'm trying to translate all routes. I'm using mcamara/laravel-localization package. My route looks like that:

    // Registration Routes...
Route::get(LaravelLocalization::transRoute('routes.register_link')/{plan?}, ['as' => 'auth.register', 'uses' => 'Auth\AuthController@showRegistrationForm']);
Route::post(LaravelLocalization::transRoute('routes.register_link'), ['as' => 'auth.register', 'uses' => 'Auth\AuthController@postRegister']);

But i'm getting eror:

syntax error, unexpected '{'

Whats wrong? Thanks for help guys!




via ром Макаров

Unable to sync conditional pivot table many to many relationship laravel

I have 2 models : Tours.php

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

Included.php

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

and below code in my TourController.php store method:

if (isset($request->includeds) && isset($request->excludeds)) {
      $tour->includes()->sync($request->includeds, false);
      $tour->excludes()->sync($request->excludeds, false);
}

when i do dd($request->includeds); I can see the coming values from the form but unable to sync it in my pivot table included_tour while the code syncs excluded_tour without any error.




via Zachary Dale

Multiple image upoad in database and showing them in Laravel

i tried to uplaod more than one image in database by doing this in controller:

public function store(request $request) {

     $pictures=[];
    $input=$request->all();
    if($file=$request->file('images'))  $pictures[]=$request->file('images');
    if($file=$request->file('image1'))  $pictures[]=$request->file('image1');
    if($file=$request->file('image2'))  $pictures[]=$request->file('image2');
    if($file=$request->file('image3'))  $pictures[]=$request->file('image3');
    if($file=$request->file('image4'))  $pictures[]=$request->file('image4');
    if($file=$request->file('image5'))  $pictures[]=$request->file('image5');
    if($file=$request->file('image6'))  $pictures[]=$request->file('image6');

     foreach($pictures as $file)


    for($name=0;$name<=7;$name++)
    {
        $name=$file->getClientOriginalName();
    }
        $file->move('image',$name);

        $input['images']=$name;
        $input['image1']=$name;
        $input['image2']=$name;
        $input['image3']=$name;
        $input['image4']=$name;
        $input['image5']=$name;
        $input['image6']=$name;




  Detail::create($input);

    return redirect('/');


}

It takes images form form and stores the selected images in public/image folder but in database it stores all the images with same image name. and while displaying also it displays the same image many time.

I know guys here have solution to this and may have better idea. so please help me out in this. thanks in advance.

The above done method was not appropriate for me so i did this in my controller

     public function uploadSubmit(request $request)
{
    // Coming soon...
    $data=$request->all();
     $imagename =[];
    $i = 0;
    $files =Input::file('images');
    foreach($files as $file){
        $extension = $file->getClientOriginalExtension();
        $imagename[$i] = 'post'.str_random(10).'.jpg';
        $destinationPath =  'assets/posts';
        $file->move($destinationPath, $imagename[$i]);
        $i++;
    }
    Detail::create($files);
        return redirect('/');
    }

And in route:

    Route::resource('/details','DetailController');

Now i am getting an error like this:FatalThrowableError in DetailController.php line 43: Call to a member function getClientOriginalName() on array. Can anyone point the problem here. thanks.




via Suz Aann shrestha

How to get last post in laravel?

Here is my table structure:

// posts
+----+--------------+---------+
| id | post_content | user_id |
+----+--------------+---------+
| 1  | content1     | 65743   |
| 2  | content2     | 24711   |
| 3  | content3     | 45541   |    -- this
| 4  | content4     | 55743   |
| 5  | content5     | 95441   |
| 6  | content6     | 45541   |    -- this
| 7  | content7     | 24711   |
| 8  | content8     | 45541   |    -- this (I want to select this one, Because it is the last one)
| 9  | content9     | 24711   |
+----+--------------+---------+

As I've commented in above, I want to get following row, assuming $user_id = 45541

| 8  | content8     | 45541   |

How can I do that in Laravel?

What I've tried so far:

$last_post = Posts::where('id', $user_id)->OrderBy('id', 'desc')->first();




via stack

Cache and Session problems in Laravel 5.3

My Laravel application was previously working great. However, after 10k user registrations on my website in one day and 100k visitors, suddenly the authentication system is failing and every refresh on my website shows you as another authenticated member.

I solved this problem by removing all files in /storage/framework/cahch and sessions folder

What is the reason of this problem and how can I solve it? ps: using laravel authentication system

update in laravel log file this is the error when session failed [2017-02-27 20:14:12] local.ERROR: exception 'ErrorException' with message 'fopen(/home/user/public_html/app/storage/framework/sessions/ztTt6PyeLtTPaAd46kY75wn3YZFbS6SZ9td9oDBU): failed to open stream: No such file or directory' in /home/user/public_html/app/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php:54




via Mohamed Magdy Elbadrawy

Doctrine Dbal Table not altered

Although i have added doctrine/dbal in composer.json and updated composer but even then facing an error

Integrity Constraint Violation: 1062 Duplicate entry '' for key ' users_oauthprovider_id_unique

  Schema::table('users', function (Blueprint $table) {
            $table->string('password')->nullable()->change();
            $table->string('oauthprovider');
            $table->string('oauthprovider_id')->unique();
        });




via Asif Nawaz

Conditional detach in many to many relationship laravel

I have 2 models Tour.php

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

Included.php

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

I'm trying to detach includeds if a tour has includeds in it while deleting a a tour.

Below code is what I have tried:

    public function destroy($id)
{
    $tour = Tour::find($id);

    if ($test = $tour->includeds()->count() != null) {
        $tour->includeds()->detach();
    }
    if ($test = $tour->excludeds()->count() != null) {
        $tour->excludeds()->detach();
    }        
    $tour->delete();

    Session::flash('success', 'The tour is sucessfully deleted.');
    return redirect()->route('tours.index');
}

The above code is generating Call to undefined method Illuminate\Database\Query\Builder::includeds() error. Please point out my mistake that i'm making.




via Tanja Forsberg

Unable to Import comma separated file (laravel 5.3)

I have 3 types of file, they can be comma separated names as

abc,xyz or it can be as abc xyz or also can be as abc,xyz abcd

I want to import above all formats in DB.At this time I am able to import only 2nd format.In other cases it imports only 1st name

My code is as follows:

$file = $request->file('file');

$name = $file->getClientOriginalName();
if ($file->extension() == 'txt' || $file->extension() == 'csv') {
   $destination = config('school.students.names');
   $file->move($destination, $name);
   chmod($destination. $name, 0777);

$delimiter = ($request->input('file') == 'csv') ? "," : "\t";
   $handle = fopen($destination.$name, 'r');
   while (($line = fgetcsv($handle, $delimiter)) !== false) {
   $name = $line;
   $data['students']   = $name[0];

   $name = Students::create($data);
 }

This time its only export 2nd format data please help to fix for others format also.

Thanks




via recovery men

Laravel 5 Search Not Working as expected

I`m new to the Laravel 5.4.i wanted to developed search when i enter id number need to fetch service from the database called new.but according to this code it is not functioning.it just show all the services without the exact value related to its id.All i want is if i enter id 1 ..i need to fetch out service related to id=1 and display it in search.blade.phpplease help me!

Here Is my Search.blade.php

 <!DOCTYPE html>
<html lang="">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>

        <!-- Fonts -->
        <link href="http://ift.tt/2dHeAcp" rel="stylesheet" type="text/css">

        <!-- Styles -->

    </head>
    <body>
       <form action="search" method="post">
       <label>Search by Id!</label><br>
       <input type="text" name="Search" /><br>
       <input type="hidden" value="" name="_token" />
       <input type="submit" name="submit" value="Search">
       </form>



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

            <thead>
                <th>Name</th>
            </thead>
            <tbody>
                @foreach($customers as $customer)

                    <td></td>

                @endforeach
            </tbody>   
        </table>

    </body>
</html>

Here is my Controller UserController

public function search_code(Request $request){

    $query = $request->search;
    $customers = DB::table('news')->where('id', 'LIKE',"%$query%")->get();
     return view('search' , compact('search', 'customers'));

    }

Here Is My Route

Route::post('search', 'UserController@search_code');




via Dasun

Laravel Pivot Table - How to increment third field with counter?

Hi guys wondering if you can help figure out what this eloquent statement should look like. It's pretty challenging, at least for me, but maybe not for some of you guys? Here is the scenario:

I have a pivot table with post_id and user_id and an additional column called "total_views" in the pivot table.

Basically what I'm trying to do is increment the views each time the user goes and view that specific post.

This is what the SQL would look like:

UPDATE post_user SET total_views = total_views+1 WHERE user_id=1 AND post_id=2

How would you write this in an eloquent statement? Big thanks for the first that can come up with a solution!




via Hanzo Miyagi

How to access other web app's data using oauth2?

Im trying to create 2 web apps. WebApp1 is for storing data(products) while WebApp2 is for the users, I would like to access data from WebApp1 using WebApp2. I understand how oauth2 works in other API like facebook and twitter. But is it possible like no need to have account in WebApp1 and just directly access data to WebApp2?

I fould this repo http://ift.tt/2lRQXDz I already made it work but I don't understand how to use it.

Thanks a lot.




via Vandolph Reyes

Laravel New Middleware not working

I have a problem in my project, i just try to fix in many hours but it still not working. I've created a new middleware - here is my code:

class CpanelAuthentication
{
    public function handle($request, Closure $next, $guard = 'player')
    {
        if (Auth::guard($guard)->check()) {
            return redirect('cpanel');
        }
        return $next($request);
    }
}

i'm just config provider and guard too. - here is my auth.php

    'guards' => [
            'web' => [
                'driver' => 'session',
                'provider' => 'users',
            ],

            'api' => [
                'driver' => 'token',
                'provider' => 'users',
            ],

            'player' => [
                'driver' => 'session',
                'provider' => 'player',
            ],
        ],

   'providers' => [
        'users' => [
            'driver' => 'database',
            'table' => 'tbl_users'
        ],

        'player' => [
            'driver' => 'database',
            'table' => 'tbl_player'
        ],
    ],

And i register this middleware in Kernel.php too - Here is my Kernel.php

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [
        'throttle:60,1',
        'bindings',
    ],

    'player' => [
        \App\Http\Middleware\CpanelAuthentication::class,
    ],
];

protected $routeMiddleware = [
    'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'player' => \App\Http\Middleware\CpanelAuthentication::class
];

And finaly i put this middleware in a route group like this:

Route::group(['middleware'  => 'player'], function() {
    Route::group(['prefix' => 'cpanel', 'namespace' => 'Cpanel'], function() {
        Route::get('/', [
            'as'    => 'getCpanel',
            'uses'  => 'CpanelController@getCpanel'
        ]);
        Route::group(['prefix' => 'investment'], function() {
            Route::get('/', [
                'as' => 'getCpanelInvestment',
                'uses' => 'InvestmentController@getCpanelInvestment'
            ]);
        });
    });
});

But the middleware not working. When i try to access the url

cpanel/investment

It's still pass the middleware and redirect inside although the user is not authenticated!

Can anyone help me ! Thanks so much !




via Train Heartnet

Laravel Polymorphic Many To Many Fetch By Specific Association

I have a simple many-to-many polymorphic relationship (if such thing is possible):

Authors

On Blog we have Posts => Authorable On Magazine, Articles => Authorable

Both relationships work as expected/documented. What I need is to fetch All authors for a specific Post Category

All I have is: Post::category('blue') Collection (category being a scope). Based on that, what is the best way to get Authors that wrote "Blue Posts" ?




via Fernando Barrocal

Avoid executing external plugins' test cases

composer.json

    "require": {
        "php": ">=5.6.4",
        "laravel/framework": "5.4.*",
        "laravel/socialite": "^3.0",
        ...
        "chencha/share": "^5.2"
    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~5.7"
    },
    ...
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },

When I run phpunit it gives me following error

PHP Fatal error: Class 'Orchestra\Testbench\TestCase' not found in /usr/lib/php5/voice/v1.5/vendor/chencha/share/tests/TestCase.php on line 3

I can add "orchestra/testbench": "~3.0" under my require-dev which will solve the issue, But is there way I can run only my test cases without the plugins' test cases?




via Saumini

How to use modelfactory in seeder in Laravel 5.4

I am using model factory in NewsTableSeeder, but I get this error when I entered db:seed.

I want to know why I can't use create() in my seeder.

Thank you.

Here is my News model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;


class News extends Model
{
    protected $table = 'news';
    protected $primaryKey = 'id';

    public function home_news_lists() {
        return $this->select('id', 'news_title', 'news_update')
                    ->orderBy('news_update', 'DESC')
                    ->limit(5)
                    ->get();
    }

    public function lists() {
        return News::all();
    }
}

Model Factories:

$factory->define(App\Models\News::class, function (Faker\Generator $faker) 
{
    static $password;
    $faker = $faker->create('zh_TW');

    return [
        'news_title'     => $faker->sentence(),
        'news_content'   => $faker->paragraph(),
        'news_author'    => $faker->name(),
        'news_pageviews' => $faker->numberBetween(1, 100),
        'news_file'      => ' ',
        'news_img'       => $faker->imageUrl($width, $height, 'business'),
        'created_at'     => $faker->dateTimeBetween('2012', 'now', 'zh_TW'),
        'updated_at'     => $faker->dateTimeBetween('2015', 'now', 'zh_TW')
    ];
});

NewsTableSeeder :

<?php

use Illuminate\Database\Seeder;

class NewsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\Models\News::class, 50)->create();
    }
}




via PH.Chen

Understanding PHP event dispatching systems

I've never done anything event-driven in PHP, only Node.js, so I'm trying to understand how event dispatching systems work in PHP (such as Laravel events, CakePHP events and Symfony event dispatcher).

This example is in the Laravel docs:

protected $listen = [
    'App\Events\OrderShipped' => [
        'App\Listeners\SendShipmentNotification',
    ],
];

Since the lifetime of a PHP script running on Apache is basically the lifetime of the request, does this mean all the event listeners are instantiated with each request?

So if I have 120 listeners in my application (i.e. listed in this $listen property), are all 120 of them going to be instantiated every time a page is visited? Or do the listener objects only get instantiated when the appropriate events are dispatched?

It seems quite inefficient for the listeners to be instantiated with each request when in the entire duration of the request there might not even be a single event fired.

Is this something that I should even be concerned about?




via rink.attendant.6

[SOLVED]Laravel 5.4 A facade root has not been set

This error is driving me crazy. I had Laravel 5.2, then I upgraded to 5.3 and then 5.4 then this error started to appear. I have searched everywhere on Google and here in SO but none of the solutions is working on my case. Any idea what to do?
enter image description here



via Albo Best

Get Model where relationship = id

Would love to know how other people are achieving the following?
Tables:
teams 
teams_users (pivot many teams, many users)
users

What i am trying to achieve
$teams->user->where('user_id', $id)->get();

however i am having to run a loop, and create another method on the team model to pluck(id, name)
    // foreach ($teams as $team) {
    //  # code...
    // dump($team->getUserIdsAttribute());
    // }

Do you know a better way?



via Harry Bosh

Uncaught TypeError: Vue.component is not a function

In OS X with Laravel/Homestead, I'm getting an error using Vue (v2.2.1). The component won't load and the console error is "Uncaught TypeError: Vue.component is not a function".

Full console error

    Uncaught TypeError: Vue.component is not a function
        at eval (eval at <anonymous> (app.js:321), <anonymous>:17:5)
        at Object.<anonymous> (app.js:321)
        at __webpack_require__ (app.js:20)
        at app.js:64
        at app.js:67  

What is throwing me off is that if I make a change to app.js, the webpack does not update to reflect any changes. So I need to A) fix the issue above, and B) figure out how to get the webpack to show updates in the console.

Any help would be greatly appreciated! I'm a noob. Here is my code...

app.js file

    Vue.component('video-upload', require('./components/VideoUpload.vue'));

    const app = new Vue({
        el: 'body'
    });

VideoUpload.vue

    <template>
        <div class="container">
            <div class="row">
                <div class="col-md-8 col-md-offset-2">
                    <div class="panel panel-default">
                        <div class="panel-heading">Example</div>

                        <div class="panel-body">
                            This is an example
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </template>

    <script>
        export default {
            mounted() {
                console.log('Component mounted.')
            }
        }
    </script>

upload.blade.php

    @extends('layouts.app')

    @section('content')
        <video-upload></video-upload>
    @endsection

package.json

    {
      "private": true,
      "scripts": {
        "prod": "gulp --production",
        "dev": "gulp watch"
      },
        "devDependencies": {
        "bootstrap-sass": "^3.3.7",
        "gulp": "^3.9.1",
        "jquery": "^3.1.0",
        "laravel-elixir": "^6.0.0-9",
        "laravel-elixir-vue": "^0.1.4",
        "laravel-elixir-webpack-official": "^1.0.2",
        "lodash": "^4.14.0",
        "video.js": "^5.11.6",
        "vue": "^2.2.1",
        "vue-resource": "^0.9.3"
      }
    }




via Stephen Pappas

Laravel Validation Extend Not Firing

I don't think that my validator extentions are working, but I can't fathom why.

Service Provider.

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Validator::extend('fail', function ($attribute, $value, $parameters, $validator) {
            return false;
        });
    }

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

}

I know the Service Provider's boot is firing because if I dd(); inside the boot method I get output. If I add a dd(); to the extend closure function, I do not get any output.

Request

class SaveOrder extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rules = [
            'customer_id' => 'in:' . Customer::getImplodedCurrentTeamKeys(),
            'pin' => 'fail'
        ];

        return $rules;
    }
}

I know the request is validating correctly because if I change the rule to 'pin' => 'required' and don't give in put I get a fail.

Why is my custom validation rule not working?




via Samuel Hawksby-Robinson

How to apply params for contextual binding interface resolving in laravel 5

I want to resolve context binding with parameters like this:

$this->app->when(ParticipantAddedToWaitingList::class)
            ->needs(NotificationParamsResolverInterface::class)
            ->give(function ($event_id, $params = []) {
                return new EventNotificationParamsResolver($event_id, $params);
            });

by using this:

app()->make(NotificationParamsResolverInterface::class, [123, [1,2,3]]);

is this possible or how could I achieve this ?

I know that contextual binding is only resolveable from constructor which does not allows to put params, am I right ?

Is there any workaround for that ?




via Rafał Łyczkowski

how to integrate firebase DB with laravel

So i'm trying to build an app for my final project and within web app and mobile app , Also i'm fascinated by firebase real time database and i wonder if there is a possibility to build my laravel app with a firebase DB and not it standard SQL DB ? i will be pleased to answer me ASP because i'm running out of time thanks in advance !




via amine hattab

Laravel multiple servers working with AWS queue

I have laravel application running in two servers (using a load balancer) and I'm wondering what happens if I put a job in a AWS SQS queue and both servers are subscribed to the queue.

  • Is there any chance that the job will be processed more than once?
  • Is there any way to setup things so the same server that put the job in the queue handles the job (think file uploads where the file is stored in disk first).

Any experience/tips/advice with this kind of setup is appreciated.




via scrubmx

Eloquent Showing pivot

for some weird reason building this model with Eloquent is hiding the Pivot that I am requiring explicitly in the relation (This Model is called Match):

public function scorers()
{
    return $this->belongsToMany(
        Player::class,
        'match_players',
        'match_id'
    )->withPivot(
        'goals'
    )->where(
        'goals', '>', 0
    );
}

public function scopeComplete($query)
{
    return $query->with(
        'homeTeam',
        'awayTeam',
        'scorers'
    );
}

The problem is the json result of scorers is as follows

"scorers": [
  {
    "id": 196,
    "name": "Tino",
    "surname": "Heck",
    "age": 24
  },...

And is hiding the pivot (goals) team_id and goals which should appear on each object inside a nested object called pivot, did anyone came across some problem like this? I cat find anything around here. Something like

"scorers": [
  {
    "id": 196,
    "name": "Tino",
    "surname": "Heck",
    "age": 24,
    "pivot": {
      "goals": 3
    }
  },...

Db structure is

Match
- id
- ..
Players
- id
- ...
MatchPlayer
- player_id
- match_id
- goals

The result inside scorers is correct, so I get the actual player where goals > 0, but not the pivot I am looking for

Thanks in advance.




via vikkio

Laravel - query returns null

Im learning laravel. And now i have a problem. I'm trying to create a form that list the cars in a cars table and if clicked, sends into another form which is based on a DB query that returns the data of the chosen car (identified by $modelesc). This form sends the data to a "orders" table. With the code that i have now, im not getting any data that i send from catalog. I choose the model and get nothing at orders. I have checked with $cars->count() on orders. it gets 0. Im using Laravel 5.4. Can anyone help me out?

This is the code

Web.php

Route::get('catalog', 'carController@catalog');
Route::get('orders/', 'CarController@orders')->name('orders');

CarController

function catalog() {
    $cars = DB::table('cars')->get();
    return view('catalog', compact('cars'));
}

function orders($modelesc=null) {
    $cars = DB::table('cars')->where('Model', $modelesc)->get();
    $colours = DB::table('colours')->get()->pluck('Colour');
    $status = DB::select('select * from order_status where id = ?', [1])->get();
    return view('orders', compact('cars', 'colours'));
}

Catalog.blade.php

@foreach($cars as $car)
{!! Form::open(array('action' => 'CarController@orders', 'method' => 'GET')) !!}
{!! Form::hidden('$modelesc', $car->Model) !!}
{!! Form::submit($car->Model) !!}
{!! Form::close() !!}   
@endforeach

Orders.blade.php

@foreach($cars as $car)
{!! Form::open(['method' => 'POST']) !!}
{!! Form::text('Model', $car->Model) !!}
{!! Form::hidden('users_id', Auth::user()->id) !!}
{!! Form::hidden('Fabrication_date', date('Y-m-d')) !!}
{!! Form::select('Colour_id', $colours) !!}
{!! Form::hidden('Order_status_id', $status) !!}
{!! Form::submit('Ok') !!}
{!! Form::close() !!}
@endforeach




via Adato

Has-Many-Through Relations

I have done a lot of research in Google about this. There are not a good examples with using this type of relation between models.

Can somebody share own sample using Has-Many-Through Relations in Laravel?




via Darama

Laravel 5.3 return Auth:user() by uniqueidentifier

It took a while, but I figured out how to succesfully authenticate a user in Laravel 5.3 using a custom user table, with custom username and password fields.

I needed to alter my User model:

protected $table        = 'Contact';    
protected $primaryKey   = 'ContactId';

public function getAuthPassword()
{
    return $this->New_hashedpassword;
}

The LoginController Http\Controllers\Auth\LoginController.php:

public function username()
{
    return 'EMailAddress1';
}

For testing, I also changed the redirection in the LoginController:

protected function redirectTo()
{
    dd(Auth::user());
}

After a successful login, the correct User model is passed to the browser.

The only problem I face now, is that this custom table uses a MSSQL uniqueidentifier as primary key. So now that when I call Auth::user()->someUserAttribute, my Laravel app throws an error:

[SQL Server]Operand type clash: uniqueidentifier is incompatible with int (SQL: select top 1 * from [Contact] where [Contact].[ContactId] = 7164)

For some reason, the actual ContactID for this user (which is a string "07164BAE-33AE-E511-AE88-000C29C93884") is converted to an int resulting in "7164".

I do not understand why the LoginController can access the Auth::user() without any problem, but anywhere else in the application accessing Auth::user() throws an error.

TIA, Wouter




via mokum

Get all championships that are teams in Eloquent

I have a tournament, a tournament can have many >

public function championships()
{
    return $this->hasMany(Championship::class);
}

and a Championship hasOne Category. In Category, I have the isTeam attribute.

Now I need a function that get me all the championships that have the isTeam = 1 in Category table.

public function teamChampionships()
{

}

Of course, I have defined : $tournament->championships, $championship->category

In my controller, I get all of them:

        $tournament = Tournament::with('championship.category')->find($tournament->id);

Any idea???




via Juliatzin del Toro

Laravel api: invalid_client

I'm trying to request a token in Laravel with Postman

But I can't get a response different than

{"error":"invalid_client","message":"Client authentication failed"}

Users in my application login with username/password :

LoginController.php contains:

public function username()
{
    return 'username';
}

And logging in on the frontend with username/password works great. So I tried both username and password as form-data, I also tried changing Body from x-www-form-urlencoded to raw and form-data both did not make a differennce. What am I doing wrong?

note: the appsecret is changed a bit to not have it public, in the real situation they match (copy pasted)




via Sven B

Laravel newbie, authentication error handle?

I have installed WAMP and its ON, also latest Laravel app.

From console I ran: php artisan make:auth

I've made all settings for db inside .env file like this:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=firstapp
DB_USERNAME=smith
DB_PASSWORD=hammerfall0

then: php artisan migrate

migrate showed some problems with database about max length, but I figured it out and fixed.

so, now after I run: php artisan serve and go to localhost:8000/register it throws me this errors:

QueryException in Connection.php line 647: SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost' (using password: YES) (SQL: select count(*) as aggregate from users where email = asd@asd.a)

and this one

PDOException in Connector.php line 68: SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost' (using password: YES)

As I understand, Laravel still tries to connect to database with homestead credential, the question is Why? if migration was successful and in phpMyAdmin tables were created...

maybe its something obvious or I messed up something, please help :)




via Eugene

how manage personal data of user in laravel?

i give data like photo's and document from users and i will save it in this path :

storage/app

i make folder for every user with this code :

$request->file('file')->store('storage/'.$request->user()->id);

name of folder is just user-id , so

is this right way , to manage personal data of user ? if its not, please give me solution,

i searched a lot but everyone just say dont do that, but what shall i do?




via Hosein

Laravel validation rules - get the broken rule name

Scenario

I am developing a multi-language website in Laravel. The languages can be added / deleted from the Admin section. The Front End section contains various forms, validated by controllers using appropriate FormRequest objects.

Problem

The validation error messages are hard-coded in their corresponding language validation.php files, which I cannot use because, well, the languages are added dynamically. It seems the MessageBag object stores only the messages and the corresponding fields but not the rule name.

My solution

I renamed all the validation messages to their corresponding rule name, removed the :attribute parts.

The question

Is there a way (ideally directly in the view) to get the failed validation rule name? For example, instead of using:



I would like to use



I hope I am clear about this. Another scenario I have is an API which, of course, validates user input. I would like to return an array with the broken rules instead of the english messages what will be difficult for a multi-language FrontEnd to accommodate.




via Alex

How to list all logged-in users in Laravel and Redis?

I'm currently making an app on Laravel (5.3) and require a list of all logged-in users. I was originally going to store them in MySQL but was advised that Redis would be better for the job. Once I looked at Redis docs I was going to store all the users in a set, but then realised you can't set an expire time on individual members, and so opted for namespaced strings instead.

I have written some code that I believe is functioning correctly, but would like advice on improving it/fixing any problems there might be.

So first, here are the two functions I added in LoginController.php

// Overriding the authenticated method from  Illuminate\Foundation\Auth\AuthenticatesUsers
protected function authenticated(Request $request, $user)
{
    $id = $user->id;

    // Getting the expiration from the session config file. Converting to seconds
    $expire = config('session.lifetime') * 60;

    // Setting redis using id as namespace and value
    Redis::SET('users:'.$id,$id);
    Redis::EXPIRE('users:'.$id,$expire);
}

//Overriding the logout method from Illuminate\Foundation\Auth\AuthenticatesUsers
public function logout(Request $request)
{
    // Deleting user from redis database when they log out
    $id = Auth::user()->id;
    Redis::DEL('users:'.$id);

    $this->guard()->logout();

    $request->session()->flush();

    $request->session()->regenerate();

    return redirect('/');
}

Next I wrote Middleware called 'RefreshRedis' in order to refresh the expiration on the Redis when the user does something that refreshes their session.

public function handle($request, Closure $next)
{
    //refreshing the expiration of users key
    if(Auth::check()){
        $id = Auth::user()->id;
        $expire = config('session.lifetime') * 60;
        Redis::EXPIRE('users:'.$id,$expire);
    }
    return $next($request);
}

I then registered the Middleware in $middlewareGroups just after the StartSession Middleware

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \App\Http\Middleware\RefreshRedis::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [
        'throttle:60,1',
        'bindings',
    ],
];

In order to get a list of all the users I used a modified version of the function found in this thread.

class Team extends AbstractWidget
{

/**
 * Treat this method as a controller action.
 * Return view() or other content to display.
 */
public function run()
{
    //Find all logged users id's from redis
    $users = $this->loggedUsers('users:*');

    return view('widgets.team',compact('users'));
}


protected function loggedUsers($pattern, $cursor=null, $allResults=array())
{
    // Zero means full iteration
    if ($cursor==="0"){
        $users = array ();

        foreach($allResults as $result){
            $users[] = User::where('id',Redis::Get($result))->first();
        }
        return $users;
    }

    // No $cursor means init
    if ($cursor===null){
        $cursor = "0";
    }

    // The call
    $result = Redis::scan($cursor, 'match', $pattern);

    // Append results to array
    $allResults = array_merge($allResults, $result[1]);

    // Get rid of duplicated values
    $allResults = array_unique($allResults);

    // Recursive call until cursor is 0
    return $this->loggedUsers($pattern, $result[0], $allResults);
}
}




via Dalek

Laravel scheduled task route helper

I have a few views in Laravel for sending e-mails. In those views, I often use the route helper provided by Laravel. This function replaces the route name by the URL of the route.

This works great, until I want to send the same e-mails from a scheduled task via

php artisan schedule:run

Then it keeps saying the route cannot be found. But as I said, the same code works great when I run it in a browser.

The e-mail part isn't important in the issue, I only mention it as a reason for wanting to use the route helper in a scheduled task. The issue is with the route helper that doesn't work when used in a scheduled task.




via Kris

Laravel scheduled tasks run with every migration

I'm trying to send an e-mail to members on their birthday in my website, created in Laravel. "Scheduled Tasks" seem to be the way to do this in Laravel, so I followed the instructions in their docs and added a call to my function in App\Console\Kernel.php like this:

protected function schedule(Schedule $schedule)
{
    $schedule->call($this->birthdayVouchers())->daily();
}

To test this, I can call

php artisan schedule:run

And this works. The e-mails are sent. But now when I want to start some migrations and seeders, the scheduled tasks also run:

php artisan migrate:refresh --seed

Why is that? If I mess something up and have to call this for some reason, I don't want all my members to receive an e-mail every time.




via Kris

[LARAVEL]Change Laravel base URL from localhost to localhost/laravel5

I'm trying to change Laravel base URL to localhost/laravel5, I tried to change APP_URL variable in .env file, I did the same changes to this line in config/app.php file:
'url' => env('APP_URL', 'http://localhost/laravel5')  

And here my /etc/apache2/sites-available/laravel.conf file:
    <VirtualHost *:80>
    ServerName localhost/laravel5

    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html/laravel5/public

    <Directory /var/www/html/laravel5>
        AllowOverride All
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

I also tried to restart apache2 service, but nothing changes



via Hamza Moslah

Laravel-5.3 use without artisan serve command?

I have a problem about laravel run without use php artisan serve command. I'm working in xampp/htdocs/works folder. I created a blog under htdocs/works folder and if i use php artisan not problem but i want to use without php artisan like localhost:8080/works/blog/ working but not find css and js files.

How can I solved it ?




via Hannik

NodeJS not working on https (port 3000)

I'm working with both laravel and nodejs (linking socket.io with redis from backend to frontend). My code on node.js file is:

var app = require('express')();
var server = require('https').Server(app);
var io = require('socket.io')(server);
const redis = require('redis');
const redisClient = redis.createClient();


server.listen(3000);

io.on('connection', function(socket){
    console.log('a user connected');
    });

redisClient.subscribe('business');
console.log("Redis server running");
redisClient.on("message", function(channel, message) {
    console.log(channel);
    console.log(message);
            io.emit(channel, message);
});

also, here is the socket.io connection.

var socket = io('https://domain.com:3000');

I keep getting:

GET http://ift.tt/2mHGXKJ;     t=1488315350710-12 net::ERR_CONNECTION_TIMED_OUT

I had this problem before on my localhost, but I solved it by setting the socket = io('domain:3000') instead of io(); because on 8080/8443 I have laravel, while on 3000 I have node.js running. I'm getting this error while having nodejs running on server (ubuntu). Thanks




via terror

[SOLVED]Unisharp laravel filemanager unable to 'browse server' in ckeditor

I have been trying to apply Unisharp Laravel Filemanager. But, the issue i am facing is that, when ever i try to insert image in CKeditor and click on 'Browse Server', a new window pops up saying that 'The requested URL was not found on this server.' which is a 404 Error. I have followed all the steps as mentioned in the docs of Unisharp Laravel Filemanager for installation and integration. Also I am using larave 5.4 and unisharp filemanager 1.6. I would be grateful to those who will try to help me. please



via aryan

Is it possible to retrieve database records inside a Blade View (Laravel)?

I know database work shouldn't be done inside the view, but unless there's another way, I think I need to do it.

In my web application, I use the same sidebar for every web page and I want to display records from a table in the sidebar. I don't want to have to retrieve those records in EVERY controller method in my application (as there is a lot).

Is it possible to do this inside a blade view? Or is there another way I should do it?




via Alex Naughton

How to set autofocus on Laravel input field using Form::text whilst still setting the class

I can't seem to set autofocus on a input field in Laravel 5.4, whilst also setting the class of the element.

What I've tried:










via JL9

Laravel API patch method

I am developing a laravel api and sucessfully made gets, posts, deletes and i am now trying to do the update method using PATCH.

Here is my first try:

public function update($id, Request $request)
{
    $taxes = taxes::find($id);
    $taxes ->fill($request->only(['$request']));
    $taxes->save();
}

And testing it with the follow url on postman

****.local/api/taxes/1?description=test

This obviously doesnt work, i tought i would be able to see the error but i am currently on a different machine but hopefully someone can guide me to correct path to make this update method.

Dont forget its an api, no views/forms.

Thank you.




via Cyanogen

React.js and Laravel

Can I make a front end with React and back end with

Laravel

? Or React is only for

Node.js

back end? If it possible, is it wise?




via James Tomatov

How to make sidebar work with custom javascript

I have a sidebar menu that I'm trying to integrate with a Laravel PHP app. The sidebar appears fine on the display page when I run the app, but the animation, dropdown, and toggle do not work when the application is run.

The HTML has no problems:

<div id="wrapper">
<div class="overlay"></div>

<!-- Sidebar -->
<nav class="navbar navbar-inverse navbar-fixed-top" id="sidebar-wrapper" role="navigation">
    <ul class="nav sidebar-nav">
        <li class="sidebar-brand">
            <a href="#">
                Brand
            </a>
        </li>
        <li>
            <a href="#">Home</a>
        </li>
        <li>
            <a href="#">About</a>
        </li>
        <li>
            <a href="#">Events</a>
        </li>
        <li>
            <a href="#">Team</a>
        </li>
        <li class="dropdown">
            <a href="#" class="dropdown-toggle" data-toggle="dropdown">Works <span class="caret"></span></a>
            <ul class="dropdown-menu" role="menu">
                <li class="dropdown-header">Dropdown heading</li>
                <li><a href="#">Action</a></li>
                <li><a href="#">Another action</a></li>
                <li><a href="#">Something else here</a></li>
                <li><a href="#">Separated link</a></li>
                <li><a href="#">One more separated link</a></li>
            </ul>
        </li>
        <li>
            <a href="#">Services</a>
        </li>
        <li>
            <a href="#">Contact</a>
        </li>
        <li>
            <a href="https://twitter.com/maridlcrmn">Follow me</a>
        </li>
    </ul>
</nav>
<!-- /#sidebar-wrapper -->

<!-- Page Content -->
<div id="page-content-wrapper">
    <button type="button" class="hamburger is-closed" data-toggle="offcanvas">
        <span class="hamb-top"></span>
        <span class="hamb-middle"></span>
        <span class="hamb-bottom"></span>
    </button>
</div>
<!-- /#page-content-wrapper -->

The CSS is also working with the sidebar

    body {
position: relative;
overflow-x: hidden;
 }
body,
html { height: 100%;}
.nav .open > a,
.nav .open > a:hover,
.nav .open > a:focus {background-color: transparent;}

/*-------------------------------*/
/*           Wrappers            */
/*-------------------------------*/

#wrapper {
padding-left: 0;
-webkit-transition: all 0.5s ease;
-moz-transition: all 0.5s ease;
-o-transition: all 0.5s ease;
transition: all 0.5s ease;
}

#wrapper.toggled {
padding-left: 220px;
}

#sidebar-wrapper {
z-index: 1000;
left: 220px;
width: 0;
height: 100%;
margin-left: -220px;
overflow-y: auto;
overflow-x: hidden;
background: #1a1a1a;
-webkit-transition: all 0.5s ease;
-moz-transition: all 0.5s ease;
-o-transition: all 0.5s ease;
transition: all 0.5s ease;
}

#sidebar-wrapper::-webkit-scrollbar {
display: none;
}

#wrapper.toggled #sidebar-wrapper {
width: 220px;
}

#page-content-wrapper {
width: 100%;
padding-top: 70px;
}

#wrapper.toggled #page-content-wrapper {
position: absolute;
margin-right: -220px;
}

/*-------------------------------*/
/*     Sidebar nav styles        */
/*-------------------------------*/

.sidebar-nav {
position: absolute;
top: 0;
width: 220px;
margin: 0;
padding: 0;
list-style: none;
}

.sidebar-nav li {
position: relative;
line-height: 20px;
display: inline-block;
width: 100%;
}

.sidebar-nav li:before {
content: '';
position: absolute;
top: 0;
left: 0;
z-index: -1;
height: 100%;
width: 3px;
background-color: #1c1c1c;
-webkit-transition: width .2s ease-in;
-moz-transition:  width .2s ease-in;
-ms-transition:  width .2s ease-in;
transition: width .2s ease-in;

}
.sidebar-nav li:first-child a {
color: #fff;
background-color: #1a1a1a;
}
.sidebar-nav li:nth-child(2):before {
background-color: #ec1b5a;
}
.sidebar-nav li:nth-child(3):before {
background-color: #79aefe;
}
.sidebar-nav li:nth-child(4):before {
background-color: #314190;
}
.sidebar-nav li:nth-child(5):before {
background-color: #279636;
}
.sidebar-nav li:nth-child(6):before {
background-color: #7d5d81;
}
.sidebar-nav li:nth-child(7):before {
background-color: #ead24c;
}
.sidebar-nav li:nth-child(8):before {
background-color: #2d2366;
}
.sidebar-nav li:nth-child(9):before {
background-color: #35acdf;
}
.sidebar-nav li:hover:before,
.sidebar-nav li.open:hover:before {
width: 100%;
-webkit-transition: width .2s ease-in;
-moz-transition:  width .2s ease-in;
-ms-transition:  width .2s ease-in;
transition: width .2s ease-in;

}

.sidebar-nav li a {
display: block;
color: #ddd;
text-decoration: none;
padding: 10px 15px 10px 30px;
}

.sidebar-nav li a:hover,
.sidebar-nav li a:active,
.sidebar-nav li a:focus,
.sidebar-nav li.open a:hover,
.sidebar-nav li.open a:active,
.sidebar-nav li.open a:focus{
color: #fff;
text-decoration: none;
background-color: transparent;
}

.sidebar-nav > .sidebar-brand {
height: 65px;
font-size: 20px;
line-height: 44px;
}
.sidebar-nav .dropdown-menu {
position: relative;
width: 100%;
padding: 0;
margin: 0;
border-radius: 0;
border: none;
background-color: #222;
box-shadow: none;
}

/*-------------------------------*/
/*       Hamburger-Cross         */
/*-------------------------------*/

.hamburger {
position: fixed;
top: 20px;
z-index: 999;
display: block;
width: 32px;
height: 32px;
margin-left: 15px;
background: transparent;
border: none;
}
.hamburger:hover,
.hamburger:focus,
.hamburger:active {
outline: none;
}
.hamburger.is-closed:before {
content: '';
display: block;
width: 100px;
font-size: 14px;
color: #fff;
line-height: 32px;
text-align: center;
opacity: 0;
-webkit-transform: translate3d(0,0,0);
-webkit-transition: all .35s ease-in-out;
}
.hamburger.is-closed:hover:before {
opacity: 1;
display: block;
-webkit-transform: translate3d(-100px,0,0);
-webkit-transition: all .35s ease-in-out;
}

.hamburger.is-closed .hamb-top,
.hamburger.is-closed .hamb-middle,
.hamburger.is-closed .hamb-bottom,
.hamburger.is-open .hamb-top,
.hamburger.is-open .hamb-middle,
.hamburger.is-open .hamb-bottom {
position: absolute;
left: 0;
height: 4px;
width: 100%;
}
.hamburger.is-closed .hamb-top,
.hamburger.is-closed .hamb-middle,
.hamburger.is-closed .hamb-bottom {
background-color: #1a1a1a;
}
.hamburger.is-closed .hamb-top {
top: 5px;
-webkit-transition: all .35s ease-in-out;
}
.hamburger.is-closed .hamb-middle {
top: 50%;
margin-top: -2px;
}
.hamburger.is-closed .hamb-bottom {
bottom: 5px;
-webkit-transition: all .35s ease-in-out;
}

.hamburger.is-closed:hover .hamb-top {
top: 0;
-webkit-transition: all .35s ease-in-out;
}
.hamburger.is-closed:hover .hamb-bottom {
bottom: 0;
-webkit-transition: all .35s ease-in-out;
}
.hamburger.is-open .hamb-top,
.hamburger.is-open .hamb-middle,
.hamburger.is-open .hamb-bottom {
background-color: #1a1a1a;
}
.hamburger.is-open .hamb-top,
.hamburger.is-open .hamb-bottom {
top: 50%;
margin-top: -2px;
}
.hamburger.is-open .hamb-top {
-webkit-transform: rotate(45deg);
-webkit-transition: -webkit-transform .2s cubic-bezier(.73,1,.28,.08);
}
.hamburger.is-open .hamb-middle { display: none; }
.hamburger.is-open .hamb-bottom {
-webkit-transform: rotate(-45deg);
-webkit-transition: -webkit-transform .2s cubic-bezier(.73,1,.28,.08);
}
.hamburger.is-open:before {
content: '';
display: block;
width: 100px;
font-size: 14px;
color: #fff;
line-height: 32px;
text-align: center;
opacity: 0;
-webkit-transform: translate3d(0,0,0);
-webkit-transition: all .35s ease-in-out;
}
.hamburger.is-open:hover:before {
opacity: 1;
display: block;
-webkit-transform: translate3d(-100px,0,0);
-webkit-transition: all .35s ease-in-out;
}

/*-------------------------------*/
/*            Overlay            */
/*-------------------------------*/

.overlay {
position: fixed;
display: none;
width: 100%;
height: 100%;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(250,250,250,.8);
z-index: 1;
}

Javascript is the part of the program that is not working.

$(document).ready(function () {
var trigger = $('.hamburger'),
    overlay = $('.overlay'),
    isClosed = false;

trigger.click(function () {
    hamburger_cross();
});

function hamburger_cross() {

    if (isClosed == true) {
        overlay.hide();
        trigger.removeClass('is-open');
        trigger.addClass('is-closed');
        isClosed = false;
    } else {
        overlay.show();
        trigger.removeClass('is-closed');
        trigger.addClass('is-open');
        isClosed = true;
    }
}

$('[data-toggle="offcanvas"]').click(function () {
    $('#wrapper').toggleClass('toggled');
});
});

This is the code that I have for the master.blade.php file in my Laravel app

<!DOCTYPE HTML>
<html>
    <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>@yield('title')</title>
    <link rel="stylesheet" href="http://ift.tt/2apRjw3" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="">
    <link rel="stylesheet" href="">
</head>
<body>
    <div class="container">
        <header class="row">
            @include('layouts.partials.sidebar')
        </header>
        <div id="main" class="row">
            @yield('content')
        </div>
    </div>

    <script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
    <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    <script src="http://ift.tt/2aHTozy" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
    <script src=""></script>
    <script src=""></script>
</body>
</html>

How do I organize the javascript files in master.blade.php file to make the sidebar work?




via metaco57

How to get same result multiple times with same inputs in laravel ORM?

i have different input fields and two of them are name_id[] and aussehen[] in the view.for example if user inputs two same value of (1,1) for the name_id and also (1,1) for the aussehen.when i run this query below.

$aussehen=Stufen::whereIN('name_id', $name_id)
         ->whereIN('stufe',$aussehen)
         ->get();

I get only one array when dd($aussehen). whereas i wanted to have two same arrays because user inputs the same values two times. But if user select two different values e.g (1,2) for name_id and (3,4) for aussehen then it shows the correct result with two arrays what i am expecting. Now is there anyway to get the same result even if user inputs the same values as much time as he wants?




via Hassan Haroon

Unable to upload image in Laravel

I am working on laravel 5.3.30 and using image intervention helper for uploading image. I am getting error "NotWritableException in Image.php line 143: Can't write image data to path (/home/test/Desktop/Laravel/blog/public/images/)" while uploading image. I have set appropriate permission to the directory but still am not able to upload image.

Code to upload image file:

if($request->hasFile('featured_image')){
            $image = $request->file('featured_image');
            $filename = time().'.'.$image->getClientOriginalExtension();
            $location = public_path('images/', $filename);
            Image::make($image)->resize(800,400)->save($location);
            $post->image = $filename;
        }

I have checked the solutions online but none it worked. Please correct me if I am doing something wrong. Thanks in advance.




via vivek321

[SOLVED]Function mcrypt_get_iv_size() is deprecated on Laravel 4

I am in L4, here is my app.php
<?php

return array(

    /*
    |--------------------------------------------------------------------------
    | Application Debug Mode
    |--------------------------------------------------------------------------
    |
    | When your application is in debug mode, detailed error messages with
    | stack traces will be shown on every error that occurs within your
    | application. If disabled, a simple generic error page is shown.
    |
    */

    'debug' => true,

    /*
    |--------------------------------------------------------------------------
    | Application URL
    |--------------------------------------------------------------------------
    |
    | This URL is used by the console to properly generate URLs when using
    | the Artisan command line tool. You should set this to the root of
    | your application so that it is used when running Artisan tasks.
    |
    */

    'url' => 'http://67.205.171.187/',

    /*
    |--------------------------------------------------------------------------
    | Application Timezone
    |--------------------------------------------------------------------------
    |
    | Here you may specify the default timezone for your application, which
    | will be used by the PHP date and date-time functions. We have gone
    | ahead and set this to a sensible default for you out of the box.
    |
    */

    'timezone' => 'UTC',

    /*
    |--------------------------------------------------------------------------
    | Application Locale Configuration
    |--------------------------------------------------------------------------
    |
    | The application locale determines the default locale that will be used
    | by the translation service provider. You are free to set this value
    | to any of the locales which will be supported by the application.
    |
    */

    'locale' => 'en',

    /*
    |--------------------------------------------------------------------------
    | Application Fallback Locale
    |--------------------------------------------------------------------------
    |
    | The fallback locale determines the locale to use when the current one
    | is not available. You may change the value to correspond to any of
    | the language folders that are provided through your application.
    |
    */

    'fallback_locale' => 'en',

    /*
    |--------------------------------------------------------------------------
    | Encryption Key
    |--------------------------------------------------------------------------
    |
    | This key is used by the Illuminate encrypter service and should be set
    | to a random, 32 character string, otherwise these encrypted strings
    | will not be safe. Please do this before deploying an application!
    |
    */

    'key' => 'rO9cCeyugcXru0VvBQ7mkP4zLLZceVgp',

    'cipher' => 'AES-256-CBC',

    /*
    |--------------------------------------------------------------------------
    | Autoloaded Service Providers
    |--------------------------------------------------------------------------
    |
    | The service providers listed here will be automatically loaded on the
    | request to your application. Feel free to add your own services to
    | this array to grant expanded functionality to your applications.
    |
    */

    'providers' => array(

        'Illuminate\Foundation\Providers\ArtisanServiceProvider',
        'Illuminate\Auth\AuthServiceProvider',
        'Illuminate\Cache\CacheServiceProvider',
        'Illuminate\Session\CommandsServiceProvider',
        'Illuminate\Foundation\Providers\ConsoleSupportServiceProvider',
        'Illuminate\Routing\ControllerServiceProvider',
        'Illuminate\Cookie\CookieServiceProvider',
        'Illuminate\Database\DatabaseServiceProvider',
        'Illuminate\Encryption\EncryptionServiceProvider',
        'Illuminate\Filesystem\FilesystemServiceProvider',
        'Illuminate\Hashing\HashServiceProvider',
        'Illuminate\Html\HtmlServiceProvider',
        'Illuminate\Log\LogServiceProvider',
        'Illuminate\Mail\MailServiceProvider',
        'Illuminate\Database\MigrationServiceProvider',
        'Illuminate\Pagination\PaginationServiceProvider',
        'Illuminate\Queue\QueueServiceProvider',
        'Illuminate\Redis\RedisServiceProvider',
        'Illuminate\Remote\RemoteServiceProvider',
        'Illuminate\Auth\Reminders\ReminderServiceProvider',
        'Illuminate\Database\SeedServiceProvider',
        'Illuminate\Session\SessionServiceProvider',
        'Illuminate\Translation\TranslationServiceProvider',
        'Illuminate\Validation\ValidationServiceProvider',
        'Illuminate\View\ViewServiceProvider',
        'Illuminate\Workbench\WorkbenchServiceProvider',
        'Sebklaus\Profiler\Providers\ProfilerServiceProvider'

    ),

    /*
    |--------------------------------------------------------------------------
    | Service Provider Manifest
    |--------------------------------------------------------------------------
    |
    | The service provider manifest is used by Laravel to lazy load service
    | providers which are not needed for each request, as well to keep a
    | list of all of the services. Here, you may set its storage spot.
    |
    */

    'manifest' => storage_path().'/meta',

    /*
    |--------------------------------------------------------------------------
    | Class Aliases
    |--------------------------------------------------------------------------
    |
    | This array of class aliases will be registered when this application
    | is started. However, feel free to register as many as you wish as
    | the aliases are "lazy" loaded so they don't hinder performance.
    |
    */

    'aliases' => array(

        'App'               => 'Illuminate\Support\Facades\App',
        'Artisan'           => 'Illuminate\Support\Facades\Artisan',
        'Auth'              => 'Illuminate\Support\Facades\Auth',
        'Blade'             => 'Illuminate\Support\Facades\Blade',
        'Cache'             => 'Illuminate\Support\Facades\Cache',
        'ClassLoader'       => 'Illuminate\Support\ClassLoader',
        'Config'            => 'Illuminate\Support\Facades\Config',
        'Controller'        => 'Illuminate\Routing\Controller',
        'Cookie'            => 'Illuminate\Support\Facades\Cookie',
        'Crypt'             => 'Illuminate\Support\Facades\Crypt',
        'DB'                => 'Illuminate\Support\Facades\DB',
        'Eloquent'          => 'Illuminate\Database\Eloquent\Model',
        'Event'             => 'Illuminate\Support\Facades\Event',
        'File'              => 'Illuminate\Support\Facades\File',
        'Form'              => 'Illuminate\Support\Facades\Form',
        'Hash'              => 'Illuminate\Support\Facades\Hash',
        'HTML'              => 'Illuminate\Support\Facades\HTML',
        'Input'             => 'Illuminate\Support\Facades\Input',
        'Lang'              => 'Illuminate\Support\Facades\Lang',
        'Log'               => 'Illuminate\Support\Facades\Log',
        'Mail'              => 'Illuminate\Support\Facades\Mail',
        'Paginator'         => 'Illuminate\Support\Facades\Paginator',
        'Password'          => 'Illuminate\Support\Facades\Password',
        'Queue'             => 'Illuminate\Support\Facades\Queue',
        'Redirect'          => 'Illuminate\Support\Facades\Redirect',
        'Redis'             => 'Illuminate\Support\Facades\Redis',
        'Request'           => 'Illuminate\Support\Facades\Request',
        'Response'          => 'Illuminate\Support\Facades\Response',
        'Route'             => 'Illuminate\Support\Facades\Route',
        'Schema'            => 'Illuminate\Support\Facades\Schema',
        'Seeder'            => 'Illuminate\Database\Seeder',
        'Session'           => 'Illuminate\Support\Facades\Session',
        'SoftDeletingTrait' => 'Illuminate\Database\Eloquent\SoftDeletingTrait',
        'SSH'               => 'Illuminate\Support\Facades\SSH',
        'Str'               => 'Illuminate\Support\Str',
        'URL'               => 'Illuminate\Support\Facades\URL',
        'Validator'         => 'Illuminate\Support\Facades\Validator',
        'View'              => 'Illuminate\Support\Facades\View',
        'Carbon'            => 'Carbon\Carbon',

    ),

);

I kept gettig
Function mcrypt_get_iv_size() is deprecated
How can I prevent that ?



via ihue

How to call scope in model?

I have the following method in model:

public function announcements()
    {
        return $this->categories()->with("announcements");
    }

And in the same model:

public function scopeActive($query)
    {
        return $query->where('votes', '>', 100);
    }

Hot to call this local scope in model for:

return $this->categories()->with("announcements")->active(); ?




via Darama

how i display image when i uplaod it using this code in laravel 5.1

I store imagepath in database like this http://localhost/shopping/public/src/img/46.png

my code :
     $imageName = $product->id . '.' . 
            $request->file('image')->getClientOriginalExtension();
            $request->file('image')->move(public_path('src/img/'.$imageName));
            $product->imagePath=$imagepath;
            $product->save();




via سرين موسى

How to create query with twice a connection to a table in Laravel 5.3?

I'm sorry my English is not good.

I need get 2 city name with once query:

For example:

City table:

+---------+----------+
|  Pana   |   Name   |
+---------+----------+
|   THR   |  Tehran  |
|   LON   |  London  |
+---------+----------+

In Model: [from_city is THR and to_city is LON]

public function scopePrintQuery($query, $id)
{
    $join = $query
        -> join('cities', 'cities.pana', 'flights.from_city')
        -> join('cities', 'cities.pana', 'flights.to_city')
        -> where('flights.id', $id)
        ->get([
            'flights.*',
            'cities.name as from_city'
            ??? for to_city?
        ]);
    return $join;
}

Now, I need get from_city name and to_city name this query. In query dose not work 2 join from one table !

How to create query?




via mySun

Add one to many in form - Backpack laravel

I'm using Backpack for Laravel to provide the backend area of my laravel website.

I'm having the following tables in my database structure:

enter image description here

This is to add sets to a match, and add matches to a tournament.

These are my Models:

Tournament Model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Backpack\CRUD\CrudTrait;

class Tournament extends Model
{
    use CrudTrait;

     /*
    |--------------------------------------------------------------------------
    | GLOBAL VARIABLES
    |--------------------------------------------------------------------------
    */

    protected $fillable = ['from', 'to', 'type', 'location', 'place'];

    /*
    |--------------------------------------------------------------------------
    | RELATIONS
    |--------------------------------------------------------------------------
    */

    public function matches()
    {
        return $this->hasMany('App\Models\Match');
    }
}

Match Model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Backpack\CRUD\CrudTrait;

class Match extends Model
{
    use CrudTrait;

     /*
    |--------------------------------------------------------------------------
    | GLOBAL VARIABLES
    |--------------------------------------------------------------------------
    */

    protected $table = 'matches';

    protected $fillable = ['opponent'];

    /*
    |--------------------------------------------------------------------------
    | RELATIONS
    |--------------------------------------------------------------------------
    */

    public function sets()
    {
        return $this->hasMany('App\Models\Set');
    }
}

Set Model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Backpack\CRUD\CrudTrait;

class Set extends Model
{
    use CrudTrait;

     /*
    |--------------------------------------------------------------------------
    | GLOBAL VARIABLES
    |--------------------------------------------------------------------------
    */

    protected $fillable = ['self', 'opponent', 'index'];

    public function match()
    {
        return $this->belongsTo('App\Models\Match');
    }
}

Now I would like to have the following when I create a Tournament in backend:

enter image description here

I can already set from, to, type, location and place. But now I would like the possibility to add a match and add sets to that match. This all on one page.

But I'm a bit stuck on how to do this. Can someone help me on my way?




via nielsv

Advertisement