mardi 1 décembre 2015

Laravel 5.1 - Problema com upload de arquivo (ERR_CONNECTION_RESET)

Minha aplicação acessa 2 bancos firebird: um para os dados e outro para arquivos. Quando faço o upload de um arquivo, ele é escrito de maneira correta no banco, mas a página fica demorando a carregar e depois mostra o erro. Fiz utilizando Ajax e notei que o arquivo é escrito 2 vezes no banco. Na primeira não mostra nenhum erro; já na segunda acontece o erro. O estranho é que não possuo nenhum loop para isso. Pego o arquivo utilizando:

file_get_contents($file_tmp); 

e para se conectar ao banco de imagens:

DB::connection('firebird2')->insert($sql, $args);

OBS.: isso só ocorre quando tento enviar o conteúdo do arquivo para o banco. Quando envio apenas a descrição, o erro não acontece.

Desde já agradeço.



via Chebli Mohamed

How to pass captured parameter in route to middleware?

If I have middleware like:

<?php namespace App\Http\Middleware;

class SomeMiddleware
{
    public function handle($request, Closure $next, $id = null)
    {
        //
    }
}

In kernel.php:

'someMiddleware'    => \App\Http\Middleware\SomeMiddleware::class,

In routes.php :

Route::put('post/{id}', ['middleware' => 'someMiddleware']);

How I can pass id captured in {id} to my middleware? I know that I can pass some custom parameter like this:

Route::put('post/{id}', ['middleware' => 'someMiddleware:16']);

But in laravel documentation there is no described how to pass argument captured in route pattern.



via Chebli Mohamed

Laravel 5.1 - passing success session to helper

I have always displayed success messages in my views with:

@if(Session::has('success'))
    <div class="alert alert-success">
        {{ Session::get('success') }}
    </div>
@endif

I'm developing a new web application in Laravel 5.1 now and I want to use a helper to display messages instead (I don't want to duplicate the HTML-code in all views). Error messages works fine, but my question is how can I access Session from a helper class?

Here is my MessageHelper with the function displaySuccessMessage() that not works:

<?php

namespace App\Helpers;

class MessageHelper {

    public static function displayErrors($errors) {

        $str = '<div class="alert alert-danger">';

        if($errors->has())
        {
            foreach ($errors->all() as $error)
            {
                $str .= sprintf('<p><i class="fa fa-times"></i> %s</p>', $error);
            }
            $str .= '</div>';
            return $str;
        }
        return null;
    }

    public static function displaySuccessMessage()
    {
        // This is not doable
        if(!Session::has('success'))
            return;

        return sprintf('<div class="alert alert-success">%s</div>', Session::get('success'));
    }
}

Is is possible to do this?



via Chebli Mohamed

eloquent using scopeSomeName() vs someName()

whats the difference between using in eloquent

class SomeModel extends Model{
    public function active(){
        return $this->where('active','=',1);
    }
}

vs:

class SomeModel extends Model{
    public function scopeActive($query){
        return $query->where('active','=',1);
    }
}

I can use them both the same way and I am getting the same results...

$SomeModel->active()->get();

is there any advantage to the "scope prepend" way?



via Chebli Mohamed

Undefined property: Illuminate\Database\Eloquent\Collection::$id

I don't know exactly why I'm getting this error as indicated by title. I am trying to write the code fro deleting records. This is the code below.

<TABLE >
            @foreach($users as $user)
                <TR><TD>{{ $user->id }}</TD><TD>{{ $user->firstname }}</TD><TD><div id="divContainer"><div class="theDiv"><form action="/users/{{ $users->id }}" method="POST"> {{ csrf_field() }} {{ method_field('DELETE') }}<button class="css-deletebutton">DELETE</button></form></div></div></TD><TD>{!! Form::submit('DEACTIVATE', ['class'=>'css-statusbutton']) !!}</TD></TR>
            @endforeach

            <!--{!! $users->render() !!}-->
    </TABLE>

This is the route:

Route::resource('users', 'UserController');

This is the controller method:

public function show($id)
    {
        $users = User::find($id);
        return view('userpages.show')->with('users', $users);
    }

This is the view to be displayed for deletion of any record.

@section('body')
    {!! Form::open([ 'method' => 'delete', 'route' => ['users.destroy', $users->id]]) !!}
    <TABLE>
        <TR><TD>{{ $users->firstname }}</TD><TD>{{ $users->lastname }}</TD><TD>{{ $users->email }}</TD><TD>{{ $users->username }}</TD><TD>{!! Form::submit('DELETE', ['class'=>'css-deletebutton']) !!}</TD></TR>
    </TABLE>
    {!! Form::close() !!}
    @stop

This is the error message I'm getting:

ErrorException in acf1a7ad2174bd2b743200b1a50b4c9f line 14:
Undefined property: Illuminate\Database\Eloquent\Collection::$id (View: C:\Users\ken4ward\Documents\xampp\htdocs\schoolproject\resources\views\userpages\index.blade.php)



via Chebli Mohamed

Laravel 5.1: Relationships with SQLite rowid?

I have a SQLite Database from another software wich I need to integrate into my own API. I started with that task (multiple databases) successfully by adding models and relations to my API in Laravel.

But now I came to an point where I cannot continue because I don't know how to build a relationship between 2 tables in that foreign DB by using the "rowid" as key.

What I've tried:

Added a usual relationship to both models like that:

Model A: Has a column named "BU_ZIMMER" that stores the "rowid" of the other Model (B)

class LdBooking extends Model
{
    protected $connection = 'lodgitDB';
    protected $table = 'b_buchungen';
    protected $primaryKey = 'rowid';
    public $timestamps = false;

    public function rentalunit()
    {
      return $this->belongsTo('App\Models\LodgitDesk\LdRentalunit', 'BU_ZIMMER', 'rowid');
  }
}

Model B: Has the rowid that is linked by other models.

class LdRentalunit extends Model
{
    protected $connection = 'lodgitDB';
    protected $table = 'o_mieteinheit';
    protected $primaryKey = 'rowid';
    public $timestamps = false;

    public function bookings()
    {
        return $this->hasMany('App\Models\LodgitDesk\LdBooking', 'rowid', 'BU_ZIMMER');
    }
}

The Controller: Fetches all data by using the "with()" method. This works perfectly for all "normal links", but not for a link to a SQLite rowid.

public function show($id)
{
    return $this->respond( LdBooking::with('rentalunit')->with('category')->select('rowid', '*')->findOrFail($id) );
}

The Result:

enter image description here

The Problem:

I think the problem is, that the standard query doesn't SELECT the rowid from a table. That's why I usually add them manually to a Eloquent-Query ->select('rowid', '*'). But I don't know how to teach my relationship, that if it's joining the other table by the key "rowid" it needs to SELECT this "rowid" first.

Is there any way to do that? Maybe modify the model? Or is it possible to workaround this problem?

I could not find a valid solution to this yet.



via Chebli Mohamed

How to return view with hashtag in Laravel 5

After saving user, I want to return to the same tab in the page with success message. How do I add hashtag in the view path or route path in laravel

if($user->save()){
            $success = "User Registered";
            return View::make('user')->with('success', $success);

When I try this, it gives me an error :-

return View::make('user#adduser')->with('success', $success);

View [user#adduser] not found

Thanks



via Chebli Mohamed