samedi 31 décembre 2016

BelongTo and pivot relationship query

I have these 3 tables

Listings

id

city


Categories

id


Items

id

category_id


Listings Table has ManytoMany Relationship with Categories Table, so there is another pivot table listing_category containing listing_id and category_id.

public function categories()
{
    return $this->belongsToMany('App\Menu', 'listing_category', 'listing_id', 'category_id')->withTimestamps();
}

Items table has BelongTo Relationship with Categories Table.

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

My goal is to build search with 2 inputs, users can search based on item name and city (which is in listings table)

example, I want to search name of item containing keyword'item A' in city containing keyword 'Los Angeles'.

How is the query to achieve this in laravel way?



via Chebli Mohamed

Laravel rest API middleware

I have a rest API where a lot of routes will be prefixed by /org/{id}. This prefix will scope the nested data and also the user will need to be checked if they are a member of the org. Would middleware be the best place to run these checks and also initialise an orgcontext class that can be accessed throughout the rest of the request?



via Chebli Mohamed

Laravel 5 autocomplete Jquery

I have a problem with my project. I want an autocomplete input that gets the data from a database, so the problem starts when I enter the view where the autocomplete input is. The view only gives me a white screen with an array that contains all the values ​​in my "clientes" table (the values for the autocomplete input are taken from this table). I think the problem may be on my routes, but I do not know what to do.

Routes:

Route::get('/nuevaVenta', 'ventas@index');
Route::get('/nuevaVenta', 'ventas@autocomplete');

Controller (ventas.php):

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Cliente;
use Illuminate\Support\Facades\Input;

class ventas extends Controller
{
    public function index(){
        return view('/nuevaVenta');
    }

    public function autocomplete(Request $Request){

        $term = Input::get('term');
        $results = array();
        $queries = Cliente::where('nombre', 'LIKE', '%'.$term.'%')
            ->orWhere('apellido_paterno', 'LIKE', '%'.$term.'%')
            ->take(10)->get();

        foreach ($queries as $query)
        {
            $results[] = [ 'id' => $query->id, 'value' => $query->nombre.' '.$query->apellido_paterno.' '.$query->apellido_materno];
        }
        return response()->json($results);
        //\Response::json($results); 
    } 
}

View (nuevaVenta.blade.php):

@extends('master')
@section('contenido')
<script src=""></script>
<script src=""></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

<form class="form-horizontal" action="" method="GET">
    <input type="hidden" name="_token" value="">
    <br>
    <div class="form-control" style="background-color: lightblue"><label>Registro de Ventas</label></div>
    <div class="col-xs-12" style="border:1px solid lightblue">
        <div class="form-group">
            <label class="control-label col-sm-12" style ="color: #4cae4c">Clave:0001</label>
        </div>
        <div class="form-group">
            <label class="control-label col-sm-1" style ="font-weight: normal">Cliente:</span></label>
            <div class="col-sm-10">
                <input type="text" name="cliente" class="form-control solo-letras" id="cliente" style="width: 40%;" placeholder="Buscar cliente..." required>
            </div>
        </div>
        <hr>
        <div class="form-group">
            <label class="control-label col-sm-1" style ="font-weight: normal">Artículo:</label>
            <div class="col-sm-10">
                <input type="text" name="cliente" class="form-control" style="width: 40%; display: inline;" placeholder="Buscar Artículo..." required>
                <a href="#" style="display: inline"><span class="glyphicon glyphicon-plus btn btn-primary"></span></a>
            </div>
        </div>
        <hr>
        <div class="col-xs-12">
            <table class="table">
              <thead class="thead-inverse">
                <tr>
                  <th>Descripción Artículo</th>
                  <th>Modelo</th>
                  <th>Cantidad</th>
                  <th>Precio</th>
                  <th>Importe</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td></td>
                </tr>
              </tbody>
            </table>
        </div>
    </div>
</form>
@stop

js file (ventas.js):

$(document).ready(function(){
    $('#cliente').autocomplete({
        autoFocus: true,
        minLength:3,
        dataType: "json",
        source:'ventas/autocomplete',
        select:function(event, ui){
            alert(ui);
        }   
    });

});

I'm using the autocomplete widget from the jquery-ui library



via Chebli Mohamed

Pre populate values in dropdown in laravel

I am trying to populate and select the option in my view.

I am able to get the value from my model in my view.

edite.blade.php template

<select id="province" type="text" class="form-control" name="province">
<option value="">Province</option>
<option value="provinceO1">Option 1</option>
<option value="provinceO2">Option 2</option>
</select>

How can i select an option with value I have from my model.

 // this help me to get value from DB



via Chebli Mohamed

laravel NotReadableException in Decoder.php - Unable to read image from file

So I am getting this error. After searching the internet it looks like the issue could be with the post_upload_size and post_size, but that's not it. I upload larger images that work fine, then this image that has 1.5MB is not working. It's like it's random. It works for some, but not for all images. Here's the full output.

Whoops, looks like something went wrong. 1/1 NotReadableException in Decoder.php line 46: Unable to read image from file (/tmp/phpVpVQeP).

in Decoder.php line 46
at Decoder->initFromPath('/tmp/phpVpVQeP') in AbstractDecoder.php line 293
at AbstractDecoder->init('/tmp/phpVpVQeP') in AbstractDriver.php line 64
at AbstractDriver->init('/tmp/phpVpVQeP') in ImageManager.php line 50
at ImageManager->make('/tmp/phpVpVQeP') in Facade.php line 215
at Facade::__callStatic('make', array('/tmp/phpVpVQeP')) in ProfileController.php line 251
at Image::make('/tmp/phpVpVQeP') in ProfileController.php line 251
at ProfileController->sendProfile(object(Request), 'klaughlin')
at call_user_func_array(array(object(ProfileController), 'sendProfile'), array(object(Request), 'username' => 'klaughlin')) in Controller.php line 256
at Controller->callAction('sendProfile', array(object(Request), 'username' => 'klaughlin')) in ControllerDispatcher.php line 164
at ControllerDispatcher->call(object(ProfileController), object(Route), 'sendProfile') in ControllerDispatcher.php line 112
at ControllerDispatcher->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 139
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in ControllerDispatcher.php line 114
at ControllerDispatcher->callWithinStack(object(ProfileController), object(Route), object(Request), 'sendProfile') in ControllerDispatcher.php line 69
at ControllerDispatcher->dispatch(object(Route), object(Request), 'App\Http\Controllers\ProfileController', 'sendProfile') in Route.php line 203
at Route->runWithCustomDispatcher(object(Request)) in Route.php line 134
at Route->run(object(Request)) in Router.php line 708
at Router->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 139
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Router.php line 710
at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 675
at Router->dispatchToRoute(object(Request)) in Router.php line 635
at Router->dispatch(object(Request)) in Kernel.php line 236
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 139
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in VerifyCsrfToken.php line 50
at VerifyCsrfToken->handle(object(Request), object(Closure))
at call_user_func_array(array(object(VerifyCsrfToken), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Cors.php line 18
at Cors->handle(object(Request), object(Closure))
at call_user_func_array(array(object(Cors), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in ShareErrorsFromSession.php line 49
at ShareErrorsFromSession->handle(object(Request), object(Closure))
at call_user_func_array(array(object(ShareErrorsFromSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in StartSession.php line 62
at StartSession->handle(object(Request), object(Closure))
at call_user_func_array(array(object(StartSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in AddQueuedCookiesToResponse.php line 37
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure))
at call_user_func_array(array(object(AddQueuedCookiesToResponse), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in EncryptCookies.php line 59
at EncryptCookies->handle(object(Request), object(Closure))
at call_user_func_array(array(object(EncryptCookies), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in CheckForMaintenanceMode.php line 44
at CheckForMaintenanceMode->handle(object(Request), object(Closure))
at call_user_func_array(array(object(CheckForMaintenanceMode), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Kernel.php line 122
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 87
at Kernel->handle(object(Request)) in index.php line 54

Here is my var_dump

object(Symfony\Component\HttpFoundation\File\UploadedFile)#30 (7) { ["test":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> bool(false) ["originalName":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> string(19) "20160212_124938.jpg" ["mimeType":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> string(10) "image/jpeg" ["size":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> int(1606199) ["error":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> int(0) ["pathName":"SplFileInfo":private]=> string(14) "/tmp/phpVpVQeP" ["fileName":"SplFileInfo":private]=> string(9) "phpVpVQeP" } string(14) "1483214733.jpg" string(76) "/home/laughlindavid/public_html/http://ift.tt/2ipj2i8"

It is odd how it just does this with certain images.

Here is the code in my controller.

        $image = Input::file('picture');
        var_dump($image);
        $filename  = time() . '.' . $image->getClientOriginalExtension();
        var_dump($filename);
        $path = public_path('profilepics/' . $filename);

var_dump($path);

            Image::make($image->getRealPath())->resize(200, 200)->save($path);
       }



via Chebli Mohamed

how to count students group by year of admission in laravel?

I try to make chart using chartsjs. I try to count students which grouped by year of admission but I'm unable to make



via Chebli Mohamed

Laravel's php artisan vendor:publish is not publishing

I have a project written on the top of Laravel 5.3. I am trying to execute php artisan vendor:publish for a specific vendor. But the command keep giving me this useless message Nothing to publish for tag [].

I don't understand why this command does not give you better info.

Here is the exact command

php artisan vendor:publish --provider="CrestApps\\CodeGenerator\\CodeGeneratorServiceProvider"

I actually went into CrestApps\CodeGenerator\CodeGeneratorServiceProvider and var dumped a message in the boot() method and I got that message. So the correct service provider is being called.

This is the code from my service provider

<?php

namespace CrestApps\CodeGenerator;

use Illuminate\Support\ServiceProvider;

class CodeGeneratorServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {

        $this->publishes([
            __DIR__ . '\\..\\config\\codegenerator.php' => config_path('codegenerator.php'),
        ]);

        $this->publishes([
            __DIR__ . '\\templates' => base_path('resources\\codegenerator-templates\\default'),
        ]);

    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->commands(
            'CrestApps\CodeGenerator\Commands\CreateControllerCommand',
            'CrestApps\CodeGenerator\Commands\CreateModelCommand',
            'CrestApps\CodeGenerator\Commands\CreateIndexViewCommand',
            'CrestApps\CodeGenerator\Commands\CreateCreateViewCommand',
            'CrestApps\CodeGenerator\Commands\CreateFormViewCommand',
            'CrestApps\CodeGenerator\Commands\CreateEditViewCommand',
            'CrestApps\CodeGenerator\Commands\CreateShowViewCommand',
            'CrestApps\CodeGenerator\Commands\CreateViewsCommand',
            'CrestApps\CodeGenerator\Commands\CreateLanguageCommand',
            'CrestApps\CodeGenerator\Commands\CreateFormRequestCommand',
            'CrestApps\CodeGenerator\Commands\CreateRoutesCommand',
            'CrestApps\CodeGenerator\Commands\CreateMigrationCommand',
            'CrestApps\CodeGenerator\Commands\CreateResourceCommand',
            'CrestApps\CodeGenerator\Commands\CreateViewLayoutCommand'
        );
    }
}

I validated that the file/folder that are being copied are correct and exists using scandir() and get_file_content()

What could be causing this problem? why no files are being copied to the destination?

There is nothing in the Laravel's log file to also help me here.



via Chebli Mohamed

where query from table with column foreign key

I have table listings and cities, listings hasOne cities relationship. there are 2 inputs, first input is to look name of listing and second input is to look name of city. Listings table has column name and city_id. Cities table has column id and name.

The goal is to look for listing in city input.

the current query look like this

$listings = Listing::where('name', 'LIKE', '%'. $request->search. '%')->where('%'. $request->location. '%', 'LIKE', function($query){
            $query->where(DB::raw('cities.name'));
        })->paginate(10);

this give error column unknow

SQLSTATE[42S22]: Column not found: 1054 Unknown column '%city input%' in 'where clause' (SQL: select count(*) as aggregate from listings where name LIKE %listing input% and %city input% LIKE (select * where cities.name is null))

any idea to fix this?



via Chebli Mohamed

Avoiding simultaneous acces to a shared resource in a web application

I have a web application consisting of users having projects , projects belong to to a single user and are access by the URI:root/project/[pid] .

Now I have a middleware to restrict users from accessing each others projects. Although I also have a feature in my web application by which an user may share their projects with other users, so multiple users can access a single shared project.

The problem is I don't want them to access the same project simultaneously , say if project1 is shared by user1 and user2 . URI root/project/project1_id could be accessed by both but not at the same time .

I am currently thinking how I could do this , I have some ideas but wanted to know if there is best or easier way to do this.

I am thinking of altering the project table in the database to have an active flag which would be set to true every time any user accesses the project web page and unset when he/she leaves the webpage or the session ends.

But I have not sure if this would be the best way to go .

I am using laravel as a framework for my web application . So a solution within that framework would be great



via Chebli Mohamed

Laravel - Using css on auth blade templates

I have a little problem on my Register / Login form that I created via php artisan:make auth. I want to use those templates but my CSS doesn't work on them.

I use gulp and sass, my welcome page take my CSS and I just cut/paste and modify the path to my form templates.

Here is the basic template (register.blade.php). You just need to pay attention to the link, beacause I didn't touch the form.

<link type="text/css" rel="stylesheet" href="">
@extends('layouts.app')
@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">Register</div>
                <div class="panel-body">
                    <form class="form-horizontal" role="form" method="POST" action="">
                        
                        <div class="form-group">
                            <label for="name" class="col-md-4 control-label">Name</label>

                            <div class="col-md-6">
                                <input id="name" type="text" class="form-control" name="name" value="" required autofocus>

                                @if ($errors->has('name'))
                                    <span class="help-block">
                                        <strong></strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="email" class="col-md-4 control-label">E-Mail Address</label>

                            <div class="col-md-6">
                                <input id="email" type="email" class="form-control" name="email" value="" required>

                                @if ($errors->has('email'))
                                    <span class="help-block">
                                        <strong></strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="password" class="col-md-4 control-label">Password</label>

                            <div class="col-md-6">
                                <input id="password" type="password" class="form-control" name="password" required>

                                @if ($errors->has('password'))
                                    <span class="help-block">
                                        <strong></strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="password-confirm" class="col-md-4 control-label">Confirm Password</label>

                            <div class="col-md-6">
                                <input id="password-confirm" type="password" class="form-control" name="password_confirmation" required>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-md-6 col-md-offset-4">
                                <button type="submit" class="btn btn-primary">
                                    Register
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

I don't know where is the problem, I use the same asset on my welcome page. My Editor says the path is the good one.

I'm here for more details and have an happy new Year full of code :)



via Chebli Mohamed

Laravel: Best way to impement dynamic routing in routes.php based on environment variable?

My aim is to roll out a big re-theming / re-skinning (including new URL routing) for a Laravel v5 project without touching the existing business logic (as much as possible that is).

This is my current approach:

  1. I placed a APP_SKIN=v2 entry in my .env file

  2. My app\Http\routes.php file has been changed as follows:

    if (env('APP_SKIN') === "v2") {
    
        # Point to the v2 controllers
        Route::get('/', 'v2\GeneralController@home' );
        ... all other v2 controllers here ...
    
    } else {
    
        # Point to the original controllers
        Route::get('/', 'GeneralController@home' );
        ... all other controllers
    
    }
    
    
  3. All v2 controllers have been placed in app/Http/Controllers/v2 and namespaced accordingly

  4. All v2 blade templates have been placed in resources/views/v2
  5. the rest of the business logic remains exactly the same and shared between the "skins".

My question: Is there a "better" way to achieve the above?. Please note that the idea here is to affect as few files as possible when doing the migration, as well as ensure that the admin can simply change an environment variable and "roll back" to the previous skin if there are problems.



via Chebli Mohamed

Laravel 5.2. Checking logged user are the owner of the page and provide authentication for action

I am developed a web application similar with facebook. User can create a page and perform action inside their page. But now i facing a problems is how can i store the page id when user posting status. Because i am using Laravel RESTful Resource to create controller. If i want to passing page id through link it does not allow cuz the route is defined as Route::resource('posts','PostController');

if i change to

Route::resource('posts/{id}','PostController');

it will occurs error.

Can i know is there any way can passing the page id other than GET function?



via Chebli Mohamed

vendredi 30 décembre 2016

What is the difference between User::class and App\User while setting relations?

return $this->belongsTo(User::class);

vs

return $this->belongsTo(App\User);

What is the difference between the above two statements?



via Chebli Mohamed

Laravel- view is not working

I am using Ubuntu 16.04 and installed Laravel 5.3 on desktop/Laravel/test directory. I have created a test.blade.php file in resources/view directory. I have also created routes.php in app/Http directory and added following code:

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

When I enter command in terminal: php artisan serve and go to http://localhost:8000 url in browser, it shows default page of laravel after installation. Why it is not showing view I have created? I have also tried writing following code in routes.php:

Route::get('/', function(){
    echo "Test";
})

But still it doesn't work. Is there anything I am missing?



via Chebli Mohamed

Call AJAX with Vue.js and Vue resource in Laravel

I'm making AJAX request in Laravel with Vue.js and Vue resource.

I have view:




<input @click="sendIt($event)" type="submit" value="Check prices" class="btn btn-success btn-theme" />


I have js:

var Vue = require('vue');
var VueResource = require('vue-resource');
Vue.use(VueResource);
Vue.http.headers.common['X-CSRF-TOKEN'] = $('meta[name=_token]').attr('content');
const app = new Vue({
el: '#app',
methods: {
sendIt: function (e)
    {
        e.preventDefault();
        var token = $('[name="_token"]').val();
        this.$http.post('/data').then((response) => {
            console.log(response);
        }, (response) => {
            console.log(response);
        });
    }
}

Route:

Route::post('/data', 'MainController@data');

And controller:

public function data() 
{
    $msg = $this->test(); //method that retrieves data from db
    return response()->json(['msg'=> $msg], 200);
}

It gives me post 500 internal server error

In response I have this headers:

Cache-Control
Content-Type
Date
Phpdebugbar-Id
Server
Status
Transfer-Encoding
X-Powered-By

In network in my data site I have response headers without token, request headers with token and I have token in Request Payload.

If I change method to get I have same error but if I change method to get and if I remove from my controller part of code where I retrieve data from db and just pass string to json (example:

$msg = 'test';
return response()->json(['msg'=> $msg], 200);

I have success and I can output test on page.

So I'm not sure if it's some problem with token or something else. I tried and this:

var token = $('[name="_token"]').val();
this.$http.post('/prices', {_token:token})

but nothing. Same error again.

If I add this:

http: {
    headers: {
  X-CSRF-TOKEN: document.querySelector('#token').getAttribute('content')
    }
},

I have syntax error on page load.

If I change to this:

http: {
    headers: {
  Authorization: document.querySelector('#token').getAttribute('content')
    }
}

I got internal server error again.

And this is my token in main view:

<meta name="csrf-token" id="token" content="">

<script>
    window.Laravel = <?php echo json_encode([
        'csrfToken' => csrf_token(),
    ]); ?>
</script>



via Chebli Mohamed

Laravel 5.3 Forgot Password raises InvalidArgumentException

I'm using Laravel 5.3 Authentication and when I use Forgot Passsword link, I get an error.

InvalidArgumentException in FileViewFinder.php line 112: No hint path defined for [notifications].

enter image description here

I have tried following options suggested by other posts in Stackoverflow.com.

  1. Modify the name of config.php project/bootstrap/cache/config.php to another name like config.php.old
  2. php artisan config:cache to clean up the cache.


via Chebli Mohamed

laravel how sort merge collections

I have 3 query, my problem is I want the merged collection to be sorted by created_at.

How to merge and sort three qurey-builder Collections?

        $posts1 =\DB::table('posts')
        ->select('posts.*', 'users.nom','pratics.titre')
        ->join('pratics', 'posts.pratic_id','=','pratics.id')
        ->join('users', 'posts.user_id','=','users.id')
        ->where('pratics.user_id',$id)
        ->orderBy('posts.id', 'desc')
        ->get();

        $posts2 =\DB::table('posts')
        ->select('posts.*', 'users.nom','pratics.titre')
        ->join('journals', 'posts.pratic_id','=','journals.id')
        ->join('users', 'posts.user_id','=','users.id')
        ->where('journals.user_id',$id)
        ->orderBy('posts.id', 'desc')
        ->get();


        $posts3 =\DB::table('posts')
        ->select('posts.*', 'users.nom','pratics.titre')
        ->join('exos', 'posts.exo_id','=','exos.id')
        ->join('users', 'posts.user_id','=','users.id')
        ->where('exos.user_id',$id)
        ->orderBy('posts.id', 'desc')
        ->get();

$posts = array_merge($posts1,$posts2, $posts3)->sortby('created_at');



via Chebli Mohamed

Laravel Relations of model to itself

I am trying to utilize a parent/child relation within one table. Each asset belongs to a parent asset, which is another asset in the assets table/asset model.

Each task in the tasks table has an asset_id record and that asset identified by the ID has a parent_asset_id in its record. I am trying to access the name field of the parent of the asset used in a task and I am getting an error. Here is the code involved:

This is the relation in the asset model:

public function parent_asset()
   {
     return $this->belongsTo('\pmms\Asset', 'parent_asset_id');
   }

and the relation in the task model

  public function asset()
   {
     return $this->belongsTo('\pmms\Asset');
   }

Ina blade file I am trying to access the name field in the asset table like this:

$task->asset->parent_asset->name

but I get the error:

Trying to get property of non-object (View: C:\pmms\resources\views\partials\tasklist.blade.php)

Where am I going wrong here?



via Chebli Mohamed

laravel 5.3: ErrorException in UrlGenerator.php line 314: Route [] not defined

Here my routes code in web.php

Route::get('/login', array("as" => "login-admin", 'uses' => 'Auth\LoginController@login'));

Controller method:

public function login()
{
    return view('admin-access.login_form');

}

Error message show: ErrorException in UrlGenerator.php line 314: Route [] not defined. (View: /var/www/html/lara_project/cust-todo/resources/views/admin-access/login_form.blade.php). How i can solve that problem.



via Chebli Mohamed

User Object returns empty when trying to set class properties in constructor

public $tracksSystemDir;
public $contentSystemDir;


public function __construct(array $attributes = [])
{
    parent::__construct($attributes);

    // setup system directory paths
    $this->tracksSystemDir = public_path() . '/users/' . $this->reference . '/tracks/';
    $this->contentSystemDir = public_path() . '/users/' . $this->reference . '/content/';
}

when i try to user $this->tracksSystemDir it returns empty, in fact User object returns empty

User {#420 ▼
  #guarded: array:1 [▶]
  #dates: array:1 [▶]
  #hidden: array:2 [▶]
  +tracksSystemDir: "/home/vagrant/Code/9mmradio/public/storage/users//tracks/"
  +contentSystemDir: "/home/vagrant/Code/9mmradio/public/storage/users//content/"
  #connection: null
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  #perPage: 15
  +incrementing: true
  +timestamps: true
  #attributes: []
  #original: []
  #relations: []
  #visible: []
  #appends: []
  #fillable: []
  #dateFormat: null
  #casts: []
  #touches: []
  #observables: []
  #with: []
  +exists: false
  +wasRecentlyCreated: false
  #forceDeleting: false
 }

This is returned user object when i dump the variable. i have googled about this and i found nothing and i went through the documentation couple of time and found nothing regarding too. So any help with this one is greatly appreciated :)



via Chebli Mohamed

How to generate a link to a LESS File using HTML::style in Laravel 5?

I use HTML::style to generate CSS file in Laravel like: {!! HTML::style('resources/css/style.css') !!} But I can't find the way to generate LESS file in Laravel.

Thanks for helping me!



via Chebli Mohamed

Laravel: Send emails only if the email is not on bounce list

I'm using Laravel 5.3 and the SES driver in order to send my emails. I've set up my database and routes so that, whenever I send an email that returns as a bounce, I get a notification and add this email to a table of "invalid emails".

Now I need to setup my app so it only sends an email if the email is NOT in this bounce table. It's a check that will be made for every single email sent by this app, with no exceptions.

Is there an easy way to make this check on the email driver, or do I need to change all calls to the Mail facade and check this before sending the email?



via Chebli Mohamed

How to configure multiple image upload in Voyager Laravel admin?

Voyager Laravel Admin offer image data_type in BREAD, by default it allows only one image. I need to upload more than one image per time. Eg: Upload image galleries that should be an array of string(image names). Adjusting the core would not be a good idea. Has anyone used to do that before?



via Chebli Mohamed

Voyager Laravel :: How create custom menu

I'm newbie for laravel. I can create list of menu but I want to route to it. I read document in How to Create Custom Menu.

Menu::display('main', 'bootstrap');
Menu::display('main', 'my_menu');

I don't know this code need to put it somewhere. Create Custom menu



via Chebli Mohamed

Header getting dropped in Laravel/PHPUnit Testing

I have a laravel 5.x app and the unit testing was working all fine. Now the php unit has stopped sending headers with http request. One of my unit tests have the following code

 $content='';

    $content = $this->post('users/login', ['password' => 'mypass',
            'email' => 'james.bond@gmail.com'])->response->getContent();

   $data = json_decode($content);
   $token = $data->token;


  $content = $this->put('users/xsettings/0', ['HTTP_Authorization' => $token])->response->getContent();

I have checked the existence for Authorization at the receiving end and found that it is not in the request.

I have tried calling $this->refreshApplication() and tried using $this->call() without luck.

Any help is appreciated.

Thanks in advance



via Chebli Mohamed

How can I use translate laravel config file

I'm using Laravel 5.3, and I've a config file, which is calling trans() function. When I run php artisan, It will give me an error

Class translator does not exist

This is my config file

<?php

return [
'modules' => [
        'name'      =>  trans('menus.module'),
        'url'       =>  'modules',
    ],
];



via Chebli Mohamed

How to unlock the file after AWS S3 Helper uploading file?

I am using the official PHP SDK with the official service provider for laravel to upload an image to Amazon S3. The image is temporarily stored on my server and should be deleted after uploading. The following is the code I used to do my upload and delete.

$temp_path = "/screenshot_temp/testing.png';

$client = AWS::createClient('s3');
$result = $client->putObject(array(
        'Bucket'     => self::$bucketName,
        'Key'        => 'screenshot/testing.png',
        'SourceFile' => $temp_path,
        'ACL'    => 'public-read'
    ));
);

chown($temp_path, 777);
unlink($temp_path);

The upload is successful. I can see my image with the link return, and I can see it on the amazon console. The problem is that the delete fails, with the following error message:

ErrorException: unlink(... path of my file ...): Permission denied

I am sure my file permission setting is correct, and I am able to delete my file with the section of code for uploading to S3 comment out. So it should be the problem that the file is locked during uploading the file. Is there a way I can unlock and delete my file?



via Chebli Mohamed

Internal server error in vue.js?

I have this method:

  addCheckbox: function() {
              if(this.field.value) {
                  this.fields.push(this.field);
                  this.field = { value: '' };
              }

              this.$http.get('/profile/checkoutAdditionalFeatures').then(function(response){
                  // True
                  data = response.data;
                  console.log(data);
                  this.$set('checkoutAdditionalFeatures', data);

              }, function(response){
                console.log(response);
                  // False
              }.bind(this));

          }

In routes i have this:

  Route::get('/profile/checkoutAdditionalFeatures', 'StandardUser\PropertiesController@checkoutAdditionalFeatures');

And in controller i have this:

public function checkoutAdditionalFeatures($additional_features){
  if(!empty($additional_features)){
    foreach($additional_features as $additional_feature){
      $data = [
         'name' => $additional_feature,
       ];
       if (!Feature::where('name', '=', $additional_feature)->exists()) {
           $additional = Feature::firstOrCreate($data);
           $additional_ids[] = $additional->id;
           return true;
       }
       return false;
    }

HTML:

  <button type="button" class="btn btn-info btn-flat bg_blue"  @click="addCheckbox"><i class="fa fa-plus"></i> Add feature</button>
  }
}

What i want is when user enter some word and click on button to check in controller if is it true or false and then return in vue.js. Then i want to display in view that word if its false.



via Chebli Mohamed

Passing parameter from route to controller in laravel

I am trying to pass a variable from route to controller. But not able to succeed.

my route entry is as below

Route::get('/Register', 'NewRegister@CheckCand');

now in the controller file I want to get one parameter. My controller function is as below

public function CheckCand()
{
    echo $ID;
}

Now how do I pass a variable ID from route to controller. But i don't want to pass it in the URL and also in get function i dont want to change '/Register'.

Route::get('/Register', 'NewRegister@CheckCand');

Means it will be like a Hidden parameter passed from route to controller. Might be question is confusing but i don't know how to explain better.



via Chebli Mohamed

How to assign relationship and fetch data using array field in laravel

There are two models: Restaurant and Category

Restaurant{
  '_id' : 12345678
  'name' : "xyz",
  'abstract' : "awdwadawdawdawd",
  'category': [1,2,3,4] //category ids
}

Category{
  '_id' : 1,
  'name' : 'PQR'
}

How can I assign relationship and fetch all the categories using that array field (category) of Restaurant in laravel 5.3 and Database is mongodb?



via Chebli Mohamed

jeudi 29 décembre 2016

How to use Basic Routing methods in Laravel?

I have get some documents from Laravel Documentation.But i can't get details clearly from that. There are lot of routing methods and how to use that for my requirements? Commonly most people are using this, but what are the other routing methods?

Route::get()
Route::post()

How to pass the message or values through this Routing? Using Controller like this is a only way?

Route::get('/app', 'AppController@index');



via Chebli Mohamed

Delete a record gave me NotFoundException in laravel 5

How can I create multiple requests for the same route like below.

Route.php

Route::get('/home', 'HomeController@index');//->middleware('auth');
Route::get('/home/{$user}','HomeController@showStudent');
Route::delete('/home/{$studentId}','HomeController@deleteStudent');

the form was working fine until I have added the delete request. In my blade template I have code something like this.

home.blade.php

  <form class="" role="form" method="DELETE" action="/home/">
                            
                            <td><button type="submit" class="btn btn-primary pull-right">Remove Student</button></td>
                            </form>

I believe because of the same routes it's showing NotFoundHTTPException.

On one route /home I am trying to Add, Show, Edit and Delete a record with different buttons.

Thanks in Advance.



via Chebli Mohamed

Pass user context id as header to rest API

I have 2 applications - a laravel rest API and angular front end which are on 2 different domains. It is a multi tenant app where users can belong to one or more organisations and can switch between orgs within the app. I am using session storage so the user can have 2 or more tabs open and be logged into different orgs at the same time. All the data belongs to an org via foreign keys etc. I need to pass the org_id with most requests and am considering doing this via a custom header e.g. X-org-id. This would work nicely with the angular http interceptors and with a laravel middleware class that can automatically scope any data reading to the org id and auto populate org if for any create/update calls.

Is there any issue with using a custom header in this way?



via Chebli Mohamed

Laravel 5.2/ Dropzone multiple file upload

I am attempting to add the ability to upload multiple files (in this case 3 PDF's), to my website. So far, I am able to get one file to upload and store in the DB. My DB column names are rates_1, rates_2 and rates_3. The file path is also not storing automatically in my DB, instead, the temp file path is being stored. If any one has any suggestions, I greatly appreciate it. I have been searching high and low and so far, below is the only way I am able to get it to work (for one image only).

My form within a modal My Controller



via Chebli Mohamed

Is possible to check how many times was called collaborator' static method in PhpSpec?

What I'm trying to achieve is:

  1. to check if factory method was called on ContextItem
  2. to check if provided entity exists in the collection

Questions:

  1. how to provide specific entity to factory method of collaborator?
  2. how to check how many times ContextItem static factory's method was called?

I'm using laravel with phpspec extension: http://ift.tt/2aQH9EB

The problem is that ->push method on Collection collaborator is not being executed from which phpspec is returning.

class ContextSpec extends ObjectBehavior
{
    function it_builds_a_collection_of_context_items(ContextItem $contextItem, Collection $collector)
    {
        $item = ContextItem::factory(1,2);
        $items = [1, 2, 3];

        $collector->push($contextItem)->shouldBeCalledTimes(3);
        $this->beConstructedThrough("factory", [$items]);

        // $collector->push($contextItem)->willReturn($item);

        // $contextItem->beConstructedThrough("factory", [0,1])->shouldBeCalled();

        // $contextItem::factory(1,2)->shouldBeCalledTimes(3);
        // $contextItem->factory()->shouldBeCalledTimes(3);

        $this->items()->shouldHaveCount(3);
        $this->items()->shouldContain($item);
    }
}

Context class:

class Context implements ContextInterface
{
    /**
     * @var Collection
     */
    private $_items;

    public static function factory($entries) {

        $items = collect([]);

        collect($entries)->each(function($value, $key) use ($items) {
            $items->push(ContextItem::factory($key, $value));
        });

        return new static($items);
    }
}



via Chebli Mohamed

Send Validator Instance key along with keys given in rule method

Issue

Validator Instance is not sending the InvalidAttempts key along with other keys. Instead, it send when the validation is passed for all keys given in rule method.

My request class is like below

class RegisterRequest extends Request
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'Password'      => 'required',
            'EmailAddress'  => 'required',
            'UserName'      => 'required'

        ];
    }    
}

I am trying to add a key which will inform user that that are left with this many attempts and for that I am writing below code and my final request class becomes like below.

class RegisterRequest extends Request
{
    use ThrottlesLogins;

    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'Password'     => 'required',
            'EmailAddress' => 'required',
            'UserName'     => 'required'            
        ];
    }

    protected function getValidatorInstance()
    {
        $instance = parent::getValidatorInstance();
        $instance->after(function ($validator) {
            $this->CheckTotalAttempts($validator);
        });
        return $instance;
    }

    public function CheckTotalAttempts($validator)
    {
        if ($this->hasTooManyRegisterAttempts($this)) {
            $validator->errors()->add('InvalidAttempts', $this->TotalAttemptsLeft($this) 
                                     . " attempts left.");
        }
    }
}



via Chebli Mohamed

Show a record and change next in the same form (next/previous record)

I would like to know how I can show a record with the next button on the same form.

I attach an example below

enter image description here

On the left side I have the data of a client (this part is fixed) and on the right side I have the data of the pets from client. Client can have several pets, but I would like to be able to see them one by one, and I can see the next pet, in the same form with the next button in the registry

I use a laravel 5 framework. Exist any way to make this (ajax?) or another better option?

I would like know example that makes this

Txh everybody



via Chebli Mohamed

TokenMismatchException on AJAX but X-CSRF-TOKEN is included in headers

I'm trying to make a POST using VueJS but I'm getting a Laravel 5.3 TokenMismatchException error.

This is in app.js to cover both jQuery and Vue:

Vue.http.interceptors.push((request, next) => {
    request.headers.set('X-CSRF-TOKEN', Laravel.csrfToken);

    next();
});

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

This is in the main.blade.php layout where we instantiate the Laravel value:

<script src="{!! asset('/js/app.js') !!}"></script>
<script>
    (function () {
        window.Laravel = {
            csrfToken: ''
        };
    })();
</script>

I've confirmed the CSRF token matches what is expected by Laravel, but still getting this error.

This is super basic stuff and I'm a bit stumped what I misconfigured here. Ideas?



via Chebli Mohamed

Retrieve models that belongsToMany specific models

I've got a standard many-to-many relationship

class User {
  public function roles() {
    return $this->belongsToMany('Role');
  }
}

class Role {
  public function users() {
    return $this->belongsToMany('User');
  }
}   

And it works very well.

But I need to select all the users that has exactly two specific roles.

$roleAdmin = Role::where('name', 'admin')->first();
$roleUser = Role::where('name', 'user')->first();

$users = //which users has BOTH $roleAdmin and $roleUser ??

Is it possible to achieve this using eloquent or I need a raw query?



via Chebli Mohamed

Laravel 5.3 - Adding DB:raw to model's 'creating' method

I have a table with different type of documents & looking for a way to insure a sub-counter is always unique for each document type. Model Invoice extends model Documents with global scope and a few accessors. I've added this to Invoice boot method :

static::creating(function(Invoice $invoice) {
  $invoice->subtype = DB::raw("(SELECT MAX(subtype) + 1 FROM Documents as 
Documents2 WHERE type = 4)");
});

This worked as long as there were no foreign key constraints on the table. It seems laravel is splitting SQL querries. First it does the DB:raw part :

insert into `documents` (`subtype`, `updated_at`, `created_at`) values    
((SELECT MAX(subtype) + 1 FROM Documents as Documents2 WHERE type = 4), ?, ?)

then it updates with other values :

update `documents` set `document_no` = ?, .... , `updated_at` = ? where `id` = ?

Now the first part always fails because of foreign keys. Is there a way to do this in 'one go' ?



via Chebli Mohamed

Laravel 5.3 DatabaseMigrations are destructive

Laravel 5.3 with mysql, PHPUnit 5.7.4

When I create a test in PHPUnit with use DatabaseMigrations;, it destroys the data that it queries.

<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ThingsTest extends TestCase
{
    use DatabaseMigrations;

    /** @test */
    public function there_are_more_than_1000_things()
    {
        $things = App\Thing::all();

        $this->assertGreaterThan(1000, count($things));
    }

Before I run phpunit, there are lots of things. After running it, mysql says ERROR 1146 (42S02): Table 'database.things' doesn't exist

Any ideas how to stop this?



via Chebli Mohamed

403 on Laravel Docker setup

I have been struggling to setup my dev enviroment based on Docker to run Laravel app. But it keeps showing me 403 Forbidden error

Below is my configuration. I tried to login to nginx container and tail -f /var/log/nginx/error.log but it does not write anything. Please guide me what i am doing wrong here.

Thanks

docker-compose.yml

version: '2'
services:
  nginx:
    build: ./nginx
    ports: 
      - "8000:80"
    volumes:
      - ./app:/usr/share/nginx/html
    environment:
      TERM: xterm
    links:
      - php
  php:
    build: ./php
    volumes:
      - ./app:/usr/share/nginx/html
    environment:
      TERM: xterm
    links:
      - mysql
  mysql:
    build: ./mysql
    volumes:
      - ./mysql/data:/var/lib/mysql
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: myapp
      MYSQL_USER: root
      MYSQL_USER: root  

Dockerfile to build nginx container

FROM nginx
MAINTAINER Raheel <raheelwp@gmail.com>

RUN rm /usr/share/nginx/html/index.html

RUN mkdir /etc/nginx/sites-available/
RUN mkdir /etc/nginx/sites-enabled/

COPY myapp.conf /etc/nginx/sites-available/myapp.conf

RUN ln -s /etc/nginx/sites-available/myapp.conf /etc/nginx/sites-

enabled/myapp.conf

Dockerfile to build PHP container

FROM php:7.0-fpm MAINTAINER Raheel

RUN apt-get update && \
    apt-get install -y curl && \
    docker-php-ext-install mysqli pdo pdo_mysql

WORKDIR /usr/share/nginx/html

RUN curl -sS http://ift.tt/SI3ujS | php -- --install-dir=/usr/local/bin --filename=composer

myapp.conf

server {

    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    root /usr/share/nginx/html/public;
    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        try_files $uri /index.php =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass php:9000; 
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

Simple route to localhost:8000

Route::get('/', function () {
    return 'Hello World';
});



via Chebli Mohamed

Concurrent issue bypass condition checking

$dailyCap = 50;   

$play = new Play;
$play->user_id = $id;
$play->prize_id = 0;
$play->prize_type = '';
$play->save(); 

DB::beginTransaction();


try
{
   $prize = $this->getPrize();

   if ($prize){
     DB::statement('update plays set prize_id = ?, prize_type = ? where id = ? and (select c from (select count(id) as c from plays where prize_id > 0 and date(created_at) = ?) as iCount) < ?;', [ $prize->id, $prize->type, $play->id,  date('Y-m-d'), $dailyCap ]);

     $play = $play->fresh();
   }

   if (is_numeric($play->prize_id) && $play->prize_id > 0) {
     $prize->user_id = $id;
     $prize->save();
   }
   else {
     $prize = null;
   }

   DB::commit();
}
catch(Exception $e){
   DB::rollback();
   $prize = null;
}

I got 2 table, one is Prizes table, another is Plays table, every time user play the game, i will determine user either get a prize or have no prize. Although i set the daily limit (50) of the prizes to be distribute in each day, it will bypass the daily capping condition due the concurrent request issue. Any hint to solve this?



via Chebli Mohamed

Get relation for multiple objects with laravel

A User has many Phones. I want to get all the phones from active users. I can do:

$phones = [];
$users = User::with('phones')->where('active', 1)->get();
foreach($users as $user) {
    $phones = array_merge($phones, $user->phones->toArray());
}
dd($phones); // <- Here are all the phones.

But I'm not sure it's the more elegant or laravel-ish way. Is there a built in magic function for such a case? Can I get all the phones from active users without writing a loop and insert in an Array?



via Chebli Mohamed

How to pass array to flash message?

I want to send array of additional_feature that they are exist to flash message. Now i only send one additional_feature. Any suggestion how can i do that?

 if(!empty($additional_features)){
          foreach($additional_features as $additional_feature){
            $data = [
               'name' => $additional_feature,
             ];
             if (!Feature::where('name', '=', $additional_feature)->exists()) {
                 $additional = Feature::firstOrCreate($data);
                 $additional_ids[] = $additional->id;
             }
             else{
               return redirect()->back()->withFlashMessage($additional_feature . ' exists!');
             }

          }
        }



via Chebli Mohamed

How to set unique for specific filed from specific table?

I have this where i have all features from database:

$features = Feature::all();

User can add new additional feature that will be added in this table, but i want to validate so if user enter something that is already in databse to get a message. So name need to be unique. Any suggestion how can i do that?

I tried this but it save it anyway.

 $this->validate($request, [
        'name' => 'unique:features',
    ]);



via Chebli Mohamed

How to properly merge more than 2 Eloquent Collections in Laravel 5.2?

My issue right now is whenever I create two new assignments, the last Post in the merged collection disappears.

// Here is the code: 
@foreach($user->groups as $group)
    <?php
    $all = $group->posts->merge($group->assignments)->merge($group->quizzes);

    $sorted = $all->sortByDesc('created_at');
    ?>
        @foreach($sorted as $item)
        <?php
        $val = get_class($item);
            switch ($val)
        {
            case 'App\Post':
            ?>
                Post:<br>    
            <?php
                break;
            case 'App\Assignment':
                ?>
                Assignment:<br>

                <?php
                break;
            case 'App\Quiz':
            ?>
                Quiz:<br>

            <?php
                break;
        }
        ?>
    @endforeach
 @endforeach

So how can I properly merge various Eloquent Collections together, then sort them by the latest?



via Chebli Mohamed

syntax error, unexpected 'firstOrCreate' (T_STRING), expecting variable (T_VARIABLE) or '$

Im getting this error when i try to do this:

  $additional_features = $request->input('additional_features');
        foreach($additional_features as $additional_feature){
          $data = [
             'name' => $additional_feature
           ];

           $additional = new Feature::firstOrCreate($data);
        }

$additional_features is an array and i try to add that, so how many items i have in array i will have that many records.Any suggestion?



via Chebli Mohamed

How to handle Not Found Resource?

when i try to visit a deleted image url i got this :

The requested resource /storage/images/5865c6789d48d96dd04ad92e7f7.jpeg was not found on this server.

So how can i handle this error or exception, so i can return formatted json instead.

I tried to handle FileNotFoundException at app\Exceptions\Handler but it didn't work

public function report(Exception $exception)
{
  if ($exception instanceof FileNotFoundException) {
    dd(json_encode['message'=>'file not found']);
  }

    parent::report($exception);
}

Thanks



via Chebli Mohamed

Laravel 5 Entrust - Users belong to many apps

I am using Entrust package in Laravel 5.3 for managing user roles and permissions, and it works perfectly.

The problem is that my users belong to many apps, so I need to check roles and permissions having into account in which app are they trying to perform the actions in each case.

As Entrust does not provide that feature out of the box... Should I add an app_id field to the pivot Entrust role_user table? Then, how would I check the roles in each case? By overriding Entrust methods?

Thanks in advance.



via Chebli Mohamed

laravel cashier Call to undefined method Illuminate\Database\Query\Builder::skipTrial()

I'm using Laravel 5.2 with Cashier package and Stripe.

in Stripe panel - Plan section - i have setted 2 plan:

  1. Basic plan with 14 day's trial
  2. Pro plan with 14 day's trial

Now if i have customer with Basic plan and he finished is Trial time. He want to change plan to Pro... I'm tring:

$client->subscription('basic')->skipTrial()->swap('pro')

in order to swap tp Pro plan without Trial period. But i keep receiving this ERROR:

BadMethodCallException in Builder.php line 2405: Call to undefined method Illuminate\Database\Query\Builder::skipTrial()

I'm following the Laravel 5.2 documentation:

Laravel 5.2 cashier

Help Please!!!!!



via Chebli Mohamed

How to access a column in laravel query result

I'm getting an error in my controller Undefined property: Illuminate\Database\Eloquent\Collection::$created_at

How can I access a column created_at from a result of laravel query?

Controller Code:

    public function getDashboard() {
        $posts=Post::latest('created_at')->get();
        dd($posts->created_at);
  //      $posts->created_at=Carbon::parse($posts->created_at)->diffForHumans(Carbon::now());
        return view('dashboard',compact('posts'));
    }

It works with findOrFail(some_id) but not with this, why?



via Chebli Mohamed

How to update a mysql table having null with some data using laravel?

I have a table called breaks. This table has columns[id, AttendanceId, start, end, breakTime, Remarks]. A user can take multiple breaks. So, this table can have multiple entries for one user. For eg: If I take 3 breaks and among 3 the first two were complete breaks(ie; it has start and end time.). However, the last break I put start and directly loggout from the system. So, the current table will be filled with 2 complete breaks and one incomplete breaks[Remarks will show Inactive for 2 breaks and Active for last break.]. Now, while logging out I have to calculate the total work time. I am taking the sums of all the breaks taken and then reduce it from : [(login time - logout time) - sum(All complete break times from break table].

Currently, my code is not considering the last break and its just taking the complete breaks sums and deducting it from the total time.

So, I tried updating the last break end time finding Active break. But I am not able to do so. Its giving me Call to a member function update() on null which is indeed correct.

How do I update the null cell, infact with the logout time so that I can consider all the breaks for calculating the total work time.

Here is my code:

$OT=Carbon::now('Asia/Kolkata');
$getRemarks = TakeBreak::orderBy('Id', 'desc')->where('AttendanceId',Session::get('AttendanceId'))->first();
if ($getRemarks->Remarks == "Active"){
   DB::table('breaks')->orderBy('Id','desc')->where('Id', Session::get('AttendanceId'))->first()
                                       ->update(
                                            [
                                                'End' => date('H:i:s', mktime(0,$OT)),
                                                'Remarks' => "Inavtive"
                                            ])
                    }



via Chebli Mohamed

Cannot change the laravel app name

I'm using php artisan app:name L&K Biomedics to set the name of the app. But I get an error saying,

'L' is not recognized as an internal or external command,
operable program or batch file.

I'm new to Laravel. What I'm doing wrong here.

enter image description here

And is there a way to undo this command? I mean, if it changed the name to L& how can I change back it?



via Chebli Mohamed

Check max attempts : Laravel 5

I have a controller action method like below. Control comes in Controller code only if validations passes in Request class below.

public function Register(RegisterRequest $request) {

}

and Request class is like this

class RegisterRequest extends Request
{

    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'Password'      => 'required',
            'EmailAddress'  => 'required',
            'UserName'      => 'required',
        ];
    }
}

Now, I am trying to write below code in case the user exceeds defined max attempts.

if ($this->hasTooManyLoginAttempts($request)) {
    return  \Response::json([
        'Status'    =>  false,
        'Message'   =>  "Attempts locked",
        'Data'      =>  null,
    ], 403);
}

I think, I should write it in Request class? but if I do so, I will need to obtain the Request class instance for hasTooManyLoginAttempts method. So, not sure how should I proceed to implement this validation

Please suggest



via Chebli Mohamed

Posting multiple modals on the same page

I have multiple modal windows to edit the user profile in my Laravel app. A modal to edit the description, one to edit Hobbies and so on. Using one modal works fine because I can post it to the profile page but the thing is, I want to post all modals to the same page and that's why is not working, I'm aware of this.

Here's what I mean:

  Route::put('/user/profile/edit','UserController@putDesc');
  Route::put('/user/profile/edit','UserController@putRate');

The modals are pretty basic forms where I set up the action to point to UserController method. How should I make the routing in this case? I hope I was clear.



via Chebli Mohamed

Laravel polymorthic relationship

I am trying to get my head around my first polymorphic relationship in Laravel 5.3.

The relationship i am trying to achieve is that an 'Editorial' will have many 'Elements' each element will be its own Model and have an order.

So for example i will have an 'ElementText', 'ElementImage', 'ElementButton' models then an 'Editorial' will have various elements assigned to it.

This is why i think i need a polymorphic relationship. I don't want multiple relationships for each element type in the 'Editorials' model, i want to be able to just get all 'Elements' regardless of its type and get it in order.

I think the idea solution would be to have an 'editorial_element' pivot table with columns like

editorial_id - integer
order - integer
element_id - integer
element_type - string

similar to the morphToManyexample in the laravel docs, but in that example you need to specify the model to morph.

So i also wondered if i should be using the morphTo() method in my Editorials model.

public function elements() {
    return $this->morphTo();
}

But i think that means i would have to add _type and _id columns to my editorials table which would be backwards (allowing one element per editorial)

Any idea if i can set the relationship i require up or am i approaching it wrong?



via Chebli Mohamed

Why are my filesystem paths differing in local machine and when hosted on VPS?

I have some storage operations being done in my controllers, this is the code that works on my local machine:

Storage::copy('public/filename.pdf', 'public/sub_directory/filename_'.$var.'.pdf');
Storage::delete('public/filename.pdf');

With this code, I am successfully able to copy a file in laravel_root/storage/app/public/, then copy and rename the file to laravel_root/storage/app/public/subdirectory/, the file in public/ gets deleted after the copy operation. This works on my local machine.

When I pushed the code up to the staging server, above paths did not work and I got ERROR: No such file or directory.

I got this working by changing the paths from what worked on the local machine to :

Storage::copy('filename.pdf', 'subdirectory/filename_'.$var.'.pdf');
Storage::delete('job_card.pdf');

I had to remove out the public/from the operations.

My question is - Why does this differ in local machine and when pushed to server?

I am running on macOS on local Machine and ubuntu 16 on the staging server. I did not change any of the config files.



via Chebli Mohamed

Table column filled later on

I'm new on Laravel and as I'm playing around with it I encounter this issue. I have a registration system which worked fine but now I wanted to add a new field in my table (description field for users). However, this description field, I don't want to be filled when the user signs up, I want the user to fill this when he gets on his profile and updates a modal window.

The problem is, if I let that filed empty, I get an error when I sign up saying that the description filed can't be empty.

This is what I use in my UserController in order to update the description field but I'm not sure if is correct.

public function postDesc(Request $request){
  $this->validate($request, [
    'description' => 'required|min:20'
  ]);
  $user = User::all();
  $user->description = $request->input('description');
  $user->save();
  return redirect()->route('user.profile.edit');
}

This is how I opened the form: {!! Form::open(['method' => 'PUT', 'action' => 'UserController@postDesc', 'class' => 'profile-form']) !!}



via Chebli Mohamed

laravel cashier stripe - how charge customer immediately when changing subscription with the same interval

I implemented laravel 5.2 with cashier (stripe). I have three plan:

  1. Basic - monthly
  2. Pro - monthly
  3. Agency - monthly

Now if i have customer that subscribe to Basic plan and he decided to subscribe to Pro plan. How can i charge him immediately with cashier?

From Stipe i got the answer that

if customer was in Basic plan and subscribe to Pro plan than hi will charge in the next charge day. but if he subscribe to a plan with a different interval (annually instead monthly) he will charge immediately.

How i can handle this bizarre situation?

let say the customer subscribe to a basic plan (the chipper one) paid it's first month. and day after change to Agency plan (much more expensive) and then he canceled is credit-card. he will enjoy almost a month if Agency plan while he only pay for the Basic plan. and at the next charge day... he won't be charged becouse his credit-card was cancelled



via Chebli Mohamed

How to execute update and delete query on sql view?

I have created a view which is showing the data from multiple tables . now I want to perform Data manipulation operations on view . How can I achieve this ?

This is my view

CREATE 
    ALGORITHM = UNDEFINED 
    DEFINER = `forge`@`%` 
    SQL SECURITY DEFINER
VIEW `contact_view` AS
    SELECT 
        `c`.`id` AS `id`,
        `c`.`fname` AS `fname`,
        `c`.`mname` AS `mname`,
        `c`.`lname` AS `lname`,
        CONCAT(`c`.`fname`, ' ', `c`.`lname`) AS `fullname`,
        `c`.`gender` AS `gender`,
        `c`.`dob` AS `dob`,
        `c`.`points` AS `points`,
        `c`.`stars` AS `star`,
        `c`.`inst_id` AS `inst_id`,
        `c`.`ingr_id` AS `ingr_id`,
        `c`.`fami_id` AS `fami_id`,
        `c`.`sour_id` AS `sour_id`,
        `c`.`image` AS `img`,
        `c`.`address` AS `address`,
        `c`.`email` AS `email`,
        `c`.`doc` AS `doc`,
        `cl`.`value` AS `mobile`,
        `p`.`district` AS `district`,
        `p`.`pincode` AS `pincode`
    FROM
        (((`contact` `c`
        JOIN `communication_link` `cl`)
        JOIN `contact_communication` `cc`)
        JOIN `pincode_db` `p`)
    WHERE
        ((`cl`.`cont_id` = `c`.`id`)
            AND (`cl`.`coco_id` = 1)
            AND (`c`.`pinc_id` = `p`.`id`))



via Chebli Mohamed

mercredi 28 décembre 2016

Upload Files directly to Amazon S3 bucket the progress bar is not working correctly using Laravel 5 and DropZone Js

Hi i am facing this issue with DropZone Js when i tries to uploads the files directly to Amazon S3 Bucket without uploading the files to server.

Whenever i upload file directly to the Amazon S3 Bucket using dropzone then the progress bar quickly reaches 100% mean while the file is still uploading on the Amazon S3 bucket and yet the DropZone js show 100% on the progress bar misleading the user. Here is my Js code

  Dropzone.autoDiscover = false;

          myDropzone = new Dropzone("div#dropzoneFileUpload", {
              url: baseUrl + "/challenge/store",
              success : function(file, response){
                alert('success')
              },

              error : function(file, response){
                this.removeAllFiles()


              },
              uploadProgress: function(progress) {
                // The event does not work when ever file is select it say 100 in alert 
                  alert(progress);
                  document.querySelector("#total-progress .progress-bar").style.width = progress + "%";
              },

              autoProcessQueue: false,
              maxFiles: 1,
              maxFilesize: 20480, // MB
              addRemoveLinks: true,
              acceptedFiles: "video/*,mp4,.mkv,.avi,.flv,.3gp,.mov,.wmv,.webm",
              params: {
                  _token: token,
              }
          });

I am using Php Laravel 5.0 on server side i am not putting file on my server i am directly uploading the file to Amazon S3 Bucket Here is my Laravel Code The file is uploading to the bucket but progress bar is not working correctly.

$file = $request->file( 'file' );
$s3 = \Storage::disk('s3');
$filePath = '/buckVideo/' . $name;
$isS3VideoUpload = $s3->put($filePath, file_get_contents($file), 'public');

the file is successfully uploaded to Amazon S3 bucket but progress bar is not working correctly.It goes to 100% directly in an instant.While the server takes time give the response.

Thanks.



via Chebli Mohamed

Getting values from checkboxes in Laravel 5

I'm working on a quote request form on my site and need some help with functionality. I'm trying to get the values from a set of checkboxes that I passed to the view; like so:

Controller (getQuote)

public function getQuote()
    {

      $services = array(
        'Accept donations',
        'Update website on your own',
        'E-Commerce',
        ...
      );

        return view('pages.quote')->withServices($services);

    }

Controller (postQuote)

public function postQuote(Request $request)
    {
      $this->validate($request, [
        'services' => 'required|array',
        ...
      ]);


      $data = array(
        'services' => $request->service,
        ...
      );

      $data['services_checked'] = Input::get('service');
      if(is_array($services_checked))
      {
      }

      Mail::send('emails.quote', $data, function($message) use ($data){
        $message->from($data['email']);
        $message->to('hi@sogenius.io');
        $message->subject('New quote request for ' .  $data['firstname'] . ' ' . $data['lastname']);

      });

      return redirect()->back()->with('message', "Thanks, your quote request has been sent");

    }

View

I then loop through the values in the passed array and display it to the user.

<article class="col-md-12 text-left services bx1-margin">
                

                
                <ul>
                @foreach ($services as $servicesid => $service)
                  <li>
                     --}}
                    <input id="" value="" name="service[]" type="checkbox" class="custom-control-input form-check-input">
                    <span class="custom-control-description"></span>
                    " name="services" type="checkbox" class="custom-control-input form-check-input"> --}}


                  </li>
                @endforeach
                </ul>
              </article>

When the user submits the form, how do I go about receiving the checked checkboxes?

Research

I saw this post here:How to get the values for a series of checkboxes in Laravel 4 controller (if checked) I saw a post her (stackoverflow) and it explains a setting the value to array[], I'm just not quite sure about implementation.



via Chebli Mohamed

How to search all posts belongs to a tag in laravel

Article Model

class Article {
    public function Tag(){
      return $this->belongsToMany('App\Tag');
    }
}

Tag Model

class Tag {
    public function Article(){
      return $this->belongsToMany('App\Article');
    }
}

pivot table

article_id === tag_id

I want to search all books use a tag's name,how can I do this?



via Chebli Mohamed

Mailgun Error 'The parameters passed to the API were invalid

I am using mailgun to help me with sending mails on laravel.

Here mail code:

$data = array('name' => ucfirst($customer_name),'email' => $email, 'ticket_id' => $ticket_id);
$mail_data = array('name' => ucfirst($customer_name),'email' => $email, 'mobile' =>  $contact, 'address' => $address, 'delivery_type' => ucfirst(Input::get('delivery_type')), 'pickup_type' => ucfirst(Input::get('pickup_type')), 'pickup_date' => $pickup_date, 'pickup_time' => $pickup_time, 'brand' => $brand_name, 'ticket_id' => $ticket_id, 'city' => $region_name);

Mailgun::send('emails.ticket', $mail_data , function($message) use($data)
{
  $message->to($data['email'], $data['name'])
          ->bcc(array('myemail@mydomain.com, aotheremail@mydomain.com, onemore@mydomain.com, lastone@mydomain.com'))
          ->subject('Service Request! - '.$data['ticket_id']);
            });

I checked the logs figured out:

[2016-12-29 05:58:58] production.ERROR: exception 'Mailgun\Connection\Exceptions\MissingRequiredParameters' with message 'The parameters passed to the API were invalid. Check your inputs! Sandbox subdomains are for test purposes only. Please add your own domain or add the address to authorized recipients in Account Settings.' in /var/www/html/mysite/vendor/mailgun/mailgun-php/src/Mailgun/Connection/RestClient.php:169
Stack trace:
#0 /var/www/html/mysite/vendor/mailgun/mailgun-php/src/Mailgun/Connection/RestClient.php(88): Mailgun\Connection\RestClient->responseHandler(Object(GuzzleHttp\Message\Response))
#1 /var/www/html/mysite/vendor/mailgun/mailgun-php/src/Mailgun/Mailgun.php(106): Mailgun\Connection\RestClient->post('sandbox798d350d...', Array, Array)
#2 /var/www/html/mysite/vendor/mailgun/mailgun-php/src/Mailgun/Mailgun.php(53): Mailgun\Mailgun->post('sandbox798d350d...', Array, Array)
#3 /var/www/html/mysite/vendor/bogardo/mailgun/src/Bogardo/Mailgun/Mailgun.php(104): Mailgun\Mailgun->sendMessage('sandbox798d350d...', Array, Array)
#4 /var/www/html/mysite/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php(222): Bogardo\Mailgun\Mailgun->send('emails.ticket', Array, Object(Closure))
#5 /var/www/html/mysite/app/Http/Controllers/AppController.php(384): Illuminate\Support\Facades\Facade::__callStatic('send', Array)
#6 /var/www/html/mysite/app/Http/Controllers/AppController.php(384): Bogardo\Mailgun\Facades\Mailgun::send('emails.ticket', Array, Object(Closure))
#7 [internal function]: App\Http\Controllers\AppController->pickup_request()
#8 /var/www/html/mysite/vendor/laravel/framework/src/Illuminate/Routing/Controller.php(256): call_user_func_array(Array, Array)
#9 /var/www/html/mysite/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(164): Illuminate\Routing\Controller->callAction('pickup_request', Array)

I am not able to figure where the problem is? is it the syntax error? or what could be wrong?

It used to work properly now it has stopped.

Thanks!



via Chebli Mohamed

Laravel 5.3 Pusher notifications not received by Echo

I'm trying to broadcast a simply test notification to a Laravel app using Pusher.

Within my web page, I've got this JavaScript to listen for the broadcast:

import Echo from 'laravel-echo'

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'notmyrealpusherkey',
    encrypted: true
});

Echo.private('App.User.')
    .notification((notification) => {
        console.log(notification);
        toastr.info(notification.message, notification.subject);
    });

My BroadcastServiceProvider is configured to validate the private channel request:

Broadcast::routes();
Broadcast::channel('App.User.*', function ($user, $user_id) {
    return (int)$user->id === (int)$user_id;
});

When I check the Pusher console, I can see that the code above successfully subscribed:

enter image description here

When I run this test, I expect it to send a notification but nothing actually shows up on the console.log or in the toastr notification browser-side:

enter image description here

The SendMessage is just a simple test notification:

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;

/**
 * Send a simple generic notification message.
 *
 * @package App\Notifications
 */
class SendMessage extends Notification
{
    use Queueable;

    /**
     * @var string
     */
    public $message = '';

    /**
     * @var string
     */
    public $subject = '';

    /**
     * @var array
     */
    private $via = ['broadcast'];

    /**
     * Create a new notification instance.
     *
     * @param string $message
     * @param string $subject
     */
    public function __construct($message, $subject = '')
    {
        $this->message = $message;
        $this->subject = $subject;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return $this->via;
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            'message' => $this->message,
            'subject' => $this->subject
        ];
    }
}

I also tried triggering it from the Laravel side, but it still doesn't reach the user's browser:

$user = User::find($this->argument('user'));

$user->notify(new SendMessage('Testing', 'Hey'));

What am I missing here?



via Chebli Mohamed

Is it possible to execute `composer dump-autoload` automatically after installing my package?

I wrote a Laravel package that I want to make available for everyone to download.

However, it seems that I have to manually execute composer dump-autoload after I add my package.

Is it possible to automatically execute composer dump-autoload after the install so that the composer will autoload all the new classes in my project?



via Chebli Mohamed

Codeception Mocking \Mail Cest

I can't seem to Mock a mail call for a codception test. This is what I'm trying, but the mocked object is never called. Does anyone have a clue why this would be the case. I'm pretty sure it's the wrong ioc object.

$I->haveBinding('mailer',function(){
    $mail = \Mockery::mock(Mailer::class);
    $mail->shouldReceive("send")->with(\Mockery::any(),\Mockery::any(),\Mockery::any())->once();

    return $mail;

});



via Chebli Mohamed

PHP maximum number of repositories

so I am developing a web app in php using Laravel framework. I have 12 Models and 1 Controller, and 12 Repositories linking to models. In each repository I am writing some functions with queries, so they are not repeated in controller. I am trying to inject repositories in controller constructor, and don't know how many of them are too many?

I heard, its 1 or 2 usualy, but I have 12 of them so far.



via Chebli Mohamed

Using RDP or RDC with godaddy windows hosting econmy?

I am wondering if anyone did access to windows hosting on godaddy econmy using rdc or rdp, I want to know to install laravel framework.



via Chebli Mohamed

How can I check if user is already logged in Laravel 5.1?

I'm trying to "discover" if user is logged in other PC, browser, device, etc.

If the user login in his smartphone (example) and press "Remember login", then try to login in PC, an TokenMismatchException occurs. If he don't press, he can login.

How can I avoid this?



via Chebli Mohamed

Laravel Eloquent insert 3 rows at once with timestamp

I'm making a site with Laravel 5.2

I would like to do is

  • INSERT 3 rows at the same time
  • The new 3 rows have to contain timestamp created_at updated_at.

With the Query Builder method insert, Yes, it does insert 3 rows at once by passing an array like:

GroupRelation::insert([
    [
        'application_id'    => $applications[0]->a_id,
        'group_id'          => $group->id,
    ],
    [
        'application_id'    => $applications[1]->a_id,
        'group_id'          => $group->id,
    ],
    [
        'application_id'    => $applications[2]->a_id,
        'group_id'          => $group->id,
    ],
]);

The code above works fine. But this cannot touch the timestamp. Which means the created_at updated_at will be null.

However, if I changed the method insert to create:

GroupRelation::create([
   ... 
]);

It received the error:

ErrorException in Model.php line 2983:
preg_match() expects parameter 2 to be string, array given

If I'm not wrong, it seems like create can just accept 1 row at the same time, right?

I know insert is not a part of Eloquent. Eloquent fires timestamps but Query Builder does not.

So my questions are:

  1. insert method can accept 3 rows at one time, but how can I fire the timestamp manually?
  2. By 1. I've tried to add 'created_at' => date('Y-m-d H:i:s'), at each items of the array. But the controller is unclear and horrible.
  3. How can I pass an array of 3 items to create method in order to fire timestamps?
  4. Is it a good idea to call create inside the loops?

PS. protected $guarded = [] was assigned to empty array so would not receive Mass Assignment Exception.

Thank you so much.



via Chebli Mohamed

Return specific value from a table to validate with in_array using Laravel

I need to return an array with the key "polls" and "polls_voted". The value of polls_voted needs to be all polls in which there is an answer.

I need to return this array to my view and make this work :

{!! link_to_route('poll.edit', 'Modifier', [$poll->id], ['class' => 'btn btn-warning btn-block' . (in_array($poll->question, $polls_voted)? ' disabled' : '')]) !!}

So i've done the following :

    $polls = Poll::paginate($n);
    $polls_answered = Poll::has('answers')->get();

    $polls_voted = [];

    foreach ($polls_answered as $poll) {
        array_push($polls_voted, $poll->question);
    }

    return compact('polls','polls_voted');

This works but I'm quite sure that there something way easier to do with eloquent or querybuilder.

Any idea ?



via Chebli Mohamed

laravel cashier - save creditcard last 4 number and expire date

I'm using laravel 5.2 with cashier package this is the form that i'm using in order to get the client creditcard token:

<form action="/your-server-side-code" method="POST">
  <script
    src="http://ift.tt/1doUtf9" class="stripe-button"
    data-key="test_token"
    data-amount="999"
    data-name="Demo Site"
    data-description="Widget"
    data-image="http://ift.tt/1HOsSjY"
    data-locale="auto">
  </script>
</form>

after it the form is submitted automatically And i get the regular answer from the server that contain the client token.

How i can save the credit-card last 4 number and expire date that the user enter?

Thank!



via Chebli Mohamed

Laravel Issue in getting record from mongo

I am using jenssegers mongodb package for connecting Laravel with mongo. I have a collection named consumer_report in which there is a key name as consumer_id which is an Object Id. i want to match with my id.but it does not show any error.

Here is my query

$val = DB::connection('mongodb')->collection('consumers_locations')->where('consumer_id','='57b33c810a56a0a81a9b50b7')->get();



via Chebli Mohamed

How to return articles if count is > 0?

I want to display only tags if have articles. Any suggestion how can i do this?

  $tags = ATags::with('articles')->whereHas('language',function($query) use($current_language_id) {
      $query->where('id','=',$current_language_id)->
    })->limit(8)
    ->get()
    ->sortByDesc(function($tag) {
        return  $tag->articles->count();
  });



via Chebli Mohamed

laravel group by query error

I am trying to get all notification list of a user group by Source_id and type and selecting 'Source_id', 'type','created_at':

    $notificationlist = Notification::select(['Source_id', 'type','created_at'])
        ->where('user_id', $user->id)
        ->groupby('Source_id','type')
        ->orderby('created_at', 'desc')
        ->get();

but i get :

SQLSTATE[42000]: Syntax error or access violation: 1055 'a.notifications.created_at' isn't in GROUP BY 
(SQL: select `Source_id`, `type`, `created_at` from `notifications` where `user_id` = 1 group by `Source_id`, `type` order by `created_at` desc)

Notification Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Notification extends Model
{
    protected $fillable = ['activity_type','type','Source_id', 'created_at'];


    public function user()
    {
        return $this->belongsTo('Cartalyst\Sentinel\Users\EloquentUser');
    }
}

schema Notification:

Schema::create('notifications', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->integer('Source_id')->unsigned();
            $table->integer('type');
            $table->integer('activity_type');
            $table->timestamps();
            $table->foreign('user_id')->references('id')->on('users')
                ->onDelete('cascade')
                ->onUpdate('cascade');
            $table->timestamps();
        });

but when i ran same query in phpmyadmin it executed successfully

enter image description here

as error says to include created_at in group by but if i include it then i can't get my desired output as all created_at timestamp is unique



via Chebli Mohamed

Laravel 5.3 validation to check whether a input value is same as given value in rule

I am using a date range and total number of days between that as another field. I wish to validate the number of days field with the duration between the date range using Laravel 5.3 validation. For example, If i give

$request->input('start_date') ="2016-12-28";
$request->input('end_date') = "2016-12-30";
$request->input('total_days') = "2";

then there should be an error saying that "the total number of days mismatch with the duration"

Please help me in achieving this.



via Chebli Mohamed

Redirecting user to a specific page

I'm using Laravel 5.3 and Auth by default with this roles package. How can i do the normal user redirection if i have similar roles and also pages for them. For example i have AdminRole and after the Login i want to redirect user to /admin/dashboard.

I tried something like this but it doesn't make sense:

protected function redirectTo()
{
    if (Auth::user()->isRole('admin'))
        return redirect()->route('admin');

    return redirect()->route('home');
}



via Chebli Mohamed

Password reset using mobile number in laravel 5.1

I want to reset my password using both mobile number and email in my application. I am using laravel 5.1. I have tried to change PasswordBroker.php But th problem is, the file PasswordBroker.php is inside vendor folder. So any changes in library update may affect the function i wrote. So i need another ways.

What changes do I have to make to request the mobile number instead of the email address when requesting a password reset with laravel's authentication.



via Chebli Mohamed

404 only on images Laravel on Apache2 Server in Ubuntu

I have a Laravel project deployed on amazon ec2 instance where all default settings are set. The routes are working correctly, even the css and javascript files are loading.

But all the images are all giving 404.

For example: <img id="logo" alt="Business" src=""></a> gets resulted into http://ift.tt/2id3EWc so the route is getting converted all right.

On my vagrant machine, it's showing correctly.

But not displaying the image. What could be the problem area, Server instance, Laravel or Apache or .htaccess settings ?



via Chebli Mohamed

mardi 27 décembre 2016

Configure navbar to show different buttons, when different type of users login Laravel 5.2

I Just wanted to ask this: I am doing a header in which I check if the user that is logged in, has an Admin or a User role. If he is an administrator, it must show Administration (the name of the button). If he is a user, it must show the name of the user's name along (the name of the button) with 2 dropdown links, profile and logout.

So far I have done this:

<li class="dropdown">
    @if ((Auth::check() && (Auth::user()->roles()->id=1)) //Administration area
        <a href="" role="button" aria-haspopup="true" aria-expanded="false" ><i class="fa fa-user fa-2x" aria-hidden="true"></i> Administration</a>
    @elseif(Auth::check() && (Auth::user()->roles()->id=3)) //Simple user area
        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false" ><i class="fa fa-user fa-2x" aria-hidden="true"></i>  <span class="caret"></span></a>
    <ul class="dropdown-menu">
        <li><a href="">User Profile</a></li>
        <li><a href="">Log out</a></li>
    </ul>
    @else
        @include('user.login') //login area
    @endif
</li>

When no users are logged in, the login button is being shown.

When a users is logged in, eg a User, it shows me Administrator button, the 1st If. But that's wrong.

It doesn't seem to get out of the If and can't see why.

I must say that I access roles table via a pivot table user_role that's why I use user()->roles()->id. When I had roles inside users table, it was working. Does anyone has any idea? Anything would be appreciated!



via Chebli Mohamed