lundi 30 novembre 2015

Laravel 5 : After login front end not accessible at same browser

I m facing a problem with laravel 5, After login when i am trying to go to WelcomeController@index page it redirect me at admin home page (4th route). my routes define

Route::get('admin' , 'Auth\AuthController@getLogin' ) ;
Route::get('/', 'WelcomeController@index');
Route::resource('fdws','FdwController'); 
Route::get('/home', ['as' => 'home', 'uses' => 'FdwController@index']);

I think this will happen because of middelware RedirectIfAuthenticated

public function handle($request, Closure $next)
    {
        if ($this->auth->check())
        {
            return new RedirectResponse(url('/home'));
        }

        return $next($request);
    }

One more thing welcome controller is for frontend no session, Can any one suggest me how can i access the welcome page index after login



via Chebli Mohamed

Laravel Validation between not converting comma separated string to array?

Just trying to do some tags validation. First checking for number of tags (as comma separated list of id's).

class SomePostRequest extends Request
{
    public function rules()
    {
        return [
            'tags' => 'between:2,5'
        ];
    }


    public function all()
    {
        $input = parent::all();

        $input['tags'] = explode(',', @$input['tags']);

        return $input;
    }

}

It keeps spititing out the message as

The tags must be between 2 and 5 characters.

Instead of the proper array message:

The :attribute must have between :min and :max items.



via Chebli Mohamed

Laravel: How to get URLs of uploaded files?

I have created an upload folder at the same level of app and storing uploaded files there. Now I need to access those file via browser so need to have an http:// based address.

First, am I doing right? What are Laravel 5.1's recommendation? Where should files be stored? If no recommendation then how do I get ULRs?



via Chebli Mohamed

App development in laravel compared to codeigniter

I am new to laravel development and confused how and where to start. I have been working on codeigniter all this while and have developed pretty huge web apps on it. Starting with laravel making a todo application or a single page site is fine but how about building a pretty good web application? How do I start my development?

Like in codeigniter I started writing all my core libraries required for my web application, all the API external calls resided in my libraries and had created set of models in the models folder of the application. There were helpers folder which allowed me to create set of helper functions which I needed before development. Coming to laravel Im confused how to start with. There is no library folder to create libraries or helper functions.There are mostly controllers and the model files remain outside and not arranged in a folder. May be my lack of experience in software development raised this question. Can someone help me on getting started up with laravel development?

  1. Where do all the external api calls resides?
  2. Is it in a controller or is there a way libraries can be build?
  3. Is base controller called a library in laravel?
  4. Where can I build my app logics in? Is it inside the controller?
  5. Laravel doc says controller just routes the http requests and does the validation.Do I have to put all my business logic inside the model files?


via Chebli Mohamed

Running the Laravel on another IP

I use ubuntu and I need to running the Laravel another IP? For example another IP: 192.168.25.9. Can someone help me?

192.169.25.9:8080/api/users



via Chebli Mohamed

remigration laravel 5 in openshift

When I was working on development, I migrated all of initial project to openshift. After several weeks add more feature, I deleted all tables in my localhost, edit the migration table and rerun the Larevel migration in local.

But now, I am trying to deploy in openshift and found that the table that I edited manually in localhost didnot executed when I push in opensfhift.

And then, I deleted all tables in openshift and push the codes, hopefully that the openshift run all migrations. But unfortunally, it's work.

Have someone experienced in this case? What I am strying to do is rerun all migrations in opensfhit.



via Chebli Mohamed

Laravel routes are not working

I have this really weird issue where the routing process on Laravel seems to not work at all.. I get NotFoundHttpException every time I try to load another route except the default one(/)

These are my files:

routes.php

<?php

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

Route::get('/test', function () {
    return "WORKING?";
});

website apache config (myquotes.conf located in /etc/apache2/sites-available)

<VirtualHost *:80>
    ServerName my.qoutes
    ServerAlias www.my.quotes
    ServerAdmin admin@my.quotes
    DocumentRoot /var/www/myquotes/public/
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

hosts rule

127.0.0.1   my.quotes

And php artisan route:list returns this

+--------+----------+------+------+---------+------------+
| Domain | Method   | URI  | Name | Action  | Middleware |
+--------+----------+------+------+---------+------------+
|        | GET|HEAD | /    |      | Closure |            |
|        | GET|HEAD | test |      | Closure |            |
+--------+----------+------+------+---------+------------+

So I don't really understand where the problem is. If I try to load /test I get the error, if I edit the function form /, nothing happens in the browser, the same view with Laravel 5 on it is shown. I have some other websites in /var/www, are those the problem or influencing it? The routes from the other websites are not working either. What should I do?

EDIT: Tested in both Chromium and Firefox and the same



via Chebli Mohamed

Laravel - sending mails - contact us form

I'm trying to setup a email sending on contact form. I've been through some guides, but nothing seems to work. I'm not good with backend, I mostly enjoy front-end.

I created a contact page, with a contact form. I'm trying to convince laravel to send the emails in my personal inbox. how do I do that? I'm using the latest email version. I also created a mailgun account, and got it verified. I would like that everything that goes through that form to be sent in my gmail address. Help and assistance would be great!



via Chebli Mohamed

How to click on something else than an achor or button in codeCeption

I am trying to build a test scenario for acceptance testing. In my scenario, I want to click on an non-editable input field to trigger a JqueryUI calendar, and then click a date from the calendar.

The problem is that I can't seem to find any actions in CodeCeption that allows you to click on something else than a an anchor or a button.

The doc clearly states : Perform a click on a link or a button, given by a locator.

public function click($link, $context = null)

There are also similar functions that do something similar, but not with the left mouse button

public function clickWithRightButton($cssOrXPath)
public function doubleClick($cssOrXPath)

This seems so trivial that I can't find anything about it. Why isn't there a clickWithLeftButton? Am I missing something here? I'm just starting with acceptance tests with CodeCeption.



via Chebli Mohamed

Float numbers in laravel form

How I limit the quantity of decimals in a input number of laravelCollective?



via Chebli Mohamed

Is it possible to deploy Laravel 5.1 on server with PHP 5.5.0

One requirement for Laravel 5.1 is PHP >= 5.5.9, and the server I have now has PHP 5.5.0. Is it possible to deploy my laravel on it? I tried multiple ways but with no luck.

Things I have done/can do:

  1. I tried add AddHandler application/x-httpd-php55 .php
  2. Tried to downgrade by change "laravel/framework": "5.1.*" to "laravel/framework": "5.0.*" in composer.json under project root, then delete vendor folder, do composer.json but I got enter image description here

Any suggestions?



via Chebli Mohamed

Insert multiple image in different tables laravel 5

I intend to create in my backend where it is possible to create workshops. In the workshops we have some data more images. How are multiple images created a table images with their relationship with the workshops. I can enter and edit the table workshops but when I want to insert images with the relationship with the portfolio I am no longer able. Someone can help me?

Controller

  public function InsertPortfolio() { 
        $portfolio = Input::except('_token'); 
        $portfolio['id'] = Input::get('id');
        $image['id_portfolio'] = Input::get('id');
        $validation = Validator::make($portfolio, Portfolio::$portfolio, ImagePortfolio::$image); 
        if ($validation->passes()) {
            if($user = Portfolio::find($portfolio['id'])) {
                $user -> update($portfolio); 
                Session::flash('editportfolio', 'Portfolio edit with success'); 
                return Redirect::to('backend/portfolio');                   
            }else{
                if($request->hasFile('image')){
                    $file = array_get($portfolio,'image');
                    $destinationPath = 'image/profile/';
                    $extension =  $request->file('image')->getClientOriginalExtension();
                    $fileName = rand(1111,9999) . '.' . $extension;
                    $file['image'] = $fileName;
                    Image::make($file)->resize(400, 400)->save($destinationPath.$fileName);
                }                   
                $user = Portfolio::insert($portfolio); 
            }
            Session::flash('portfolio', 'Portfolio insert with success'); 
            return Redirect::to('backend/portfolio');
        } else { 
            return Redirect::to('backend/portfolio/edit/'.$portfolio['id'])->withInput()->withErrors($validation); 
        }   
    }

Model

class ImagePortfolio extends Model
{
    protected $table = 'imageportfolio';

protected $fillable = ['id','id_portfolio','image'];

public static $imageportfolio = array(
        'image' => 'image|max:3000|mimes:jpeg,jpg,png'
        );      
}




 class Portfolio extends Model
{
    protected $table = 'portfolio';

    protected $fillable = ['id','title','year','description','sex'];

    public function imageportfolio(){ 
        return $this->hasMany('App\ImagePortfolio','id_portfolio','id')->first(); 
    }

    public static $portfolio = array(
            'title' =>  'required',
            'year' =>  'required',
            'description' =>  'required',
            'sex' =>  'required',
            );      
}



via Chebli Mohamed

Laravel log errors in production

In my Laravel 5.1 application, I've set APP_DEBUG to false for my production environment. However, I'd still like to see errors (exceptions) being logged to the log file.

In app/Exceptions/Handler.php I see the following method:

public function report(Exception $e)
{
    return parent::report($e);
}

where the parent::report method uses LoggerInterface to log errors. So I expect this already being taken care of for me. Nevertheless I don't see exceptions in my logfile. Only the "Whoops, looks like something went wrong." message.

How can I achieve this?



via Chebli Mohamed

Session::flash not working in ajax laravel 5

I have action named getuser which is called by ajax.

Here is my ajax

var $_token = $('#token').val();
var BASE = "{{ URL::to('/') }}";
$.ajax({
        url: BASE + "/admin/user/test",
        type: 'POST',
        data: {type:type, id:id},
        headers: { 'X-XSRF-TOKEN' : $_token },
        success: function(data){
            // Success...
            console.log(data);
            location.reload();
        }
    }); 

Controller action,

public function getuser()
{
    Session::flash('message', 'This is a message!'); 
    Session::flash('alert-class', 'alert-danger');
    exit;
}

And into view i have code like this,

@if(Session::has('message'))
    <p class="alert {{ Session::get('alert-class', 'alert-info') }}">{{ Session::get('message') }}</p>
@endif

But not working for me. Any suggestion?



via Chebli Mohamed

Laravel 5.1 Task Scheduling command issue

I am trying to execute two console commands.Below is my two commands in my Kernel.php

protected function schedule(Schedule $schedule)
{
    $schedule->command('users:get')->everyMinute();

    $schedule->command('users:update')->dailyAt('01:00');
}

When I run php artisan schedule:run, Only the command which is/are scheduled as everyMinute is scheduled.

Running scheduled command: '/usr/bin/php5' 'artisan' users:get > /dev/null 2>&1 &

If I change the dailyAt to everyMinute for the second command, both are scheduled as shown below

Running scheduled command: '/usr/bin/php5' 'artisan' users:get > /dev/null 2>&1 &

Running scheduled command: '/usr/bin/php5' 'artisan' users:update > /dev/null 2>&1 &



via Chebli Mohamed

How to insert form values in two different database table in laravel 5.1

How should I save values of form in two different tables in database using laravel. I have two tables one is saving only email and password, second is storing other information of user. How should I do this?



via Chebli Mohamed

Routing in Laravel module

I created a module in Laravel 5 i.e inside the same level as the app folder as part of making an HMVC structure in Laravel. I have two modules in the module folder, one being a project folder and another a form folder. Now I got the controller, model and view inside these folders.

Click here to view folder structure

Now when i try to access my controller like

Route::controller('project/dashboard', 'ProjectController@index');

I get error

ReflectionException in ControllerInspector.php line 35:
Class ProjectController does not exist

I would like to know about routing a controller in modular structure in Laravel.



via Chebli Mohamed

How to use Elasticsearch and Shield with Laravel 5?

Elasticsearch packages existed for laravel 5 in git-hub but for securing elastic another package shield is existed. now i want to know how we can use that shield package with laravel elasticsearch packge, or is there any package in laravel that integrated with shield or no. any guide just for starting this. Thanks.



via Chebli Mohamed

Pass variable from route to controller in Laravel 5

Is there any way to pass the $_SERVER['REQUEST_URI'] variable to the controller in Laravel 5?



via Chebli Mohamed

Laravel 5 Route group controllers

Now I am writing routes like this:

Route::group(['prefix' => 'v2/'], function(){
    Route::post('/reg', 'UserController@reg');
    Route::post('/login', 'UserController@login');
    ...
});

Is there any way to make routes like this :

Route::group(['prefix' => 'v2/'], function(){
    Route::group(['uses' => 'UserController'], function(){
        Route::post('/reg', '@reg');
        Route::post('/login','@login');
        ...
    });
});



via Chebli Mohamed

Laravel Intervention Image Class - Class 'Image' not found

i'm trying to install 'intervention/image` from composer, but after install that i get this error:

Class 'Image' not found

1: install via composer:

composer require intervention/image 

2: add to providers array:

'Intervention\Image\ImageServiceProvider' 

3: add to aliases array:

'Image' => 'Intervention\Image\Facades\Image'

4: upadte composer

composer update

5: publish:

php artisan vendor:publish --provider="Intervention\Image\ImageServiceProviderLaravel5" 

public result:

Nothing to publish for tag [].

6: autoload

composer dump-autoload



via Chebli Mohamed

NotReadableException in Laravel with Glide and Intervention Image

I have fairly simple site in Laravel 5 with few static pages. One of features site uses is Glide server for image manipulation so in my composer.json I have this line

"league/glide": "0.3.*",

Apparently as a dependancy this package is also installed

"intervention/image": "~2.1",

Now it seems like I've set everything up, but when I try hitting some image via url, I get

NotReadableException in Decoder.php line 21:
Unable to read image from file (/tmp/GlidesCmrgC).

Where everything after Glide in tmp file name is random. So obviously file is loaded and not missing, but still something is going wrong. I was looking into documentation, but couldn't find anything.

Here is an ImageController file that is routed to handle Glide requests

<?php 
namespace app\Http\Controllers;

use Illuminate\Http\Request;
use League\Glide\Server as GlideServer;

class ImageController extends Controller
{
    public function output(Request $request, GlideServer $glide)
    {
        // Also tried this 
        // $glide->outputImage($request);
        $glide->getImageResponse($request);
    }
}

In my AppServiceProvider.php I have this part

$this->app->singleton('League\Glide\Server', function ($app) {

        $filesystem = $app->make('Illuminate\Contracts\Filesystem\Filesystem');
        return \League\Glide\ServerFactory::create([
            'source' => $filesystem->getDriver(),
            'cache' => $filesystem->getDriver()
        ]);

        // Also tried this 
        // $filesystem = $app->make('League\Flysystem\FilesystemInterface');

        /* return \League\Glide\ServerFactory::create([
            'source' => $filesystem,
            'cache' => storage_path().'/app/.cache',
            'base_url' => 'img',
        ]); */
    });

And in routes.php I have this route

get('/img/{path}', 'ImageController@output');



via Chebli Mohamed

Laravel Access to several tables

I'm having an issue in accessing to data that are related in more than one table, here my code:

<table class="table table-striped">
    <thead>
        <th>Ejercicio</th>
        <th>Unidad</th>
        <th>Descripcion</th>
        <th>Tipo actividad</th>
        <th>Operaciones</th>
    </thead>
    @foreach($exercises as $exercise)
    <tbody>
        <td>{{$exercise->name}}</td>
        <td>{{$exercise->unit}}</td>
        <td>{{$exercise->description}}</td>
        <td>{{$exercise->activity_id}}</td>
        <td>
            <?php echo link_to('exercise/edit/'.$exercise->id, $title = 'Editar', $attributes = array('class' => 'btn btn-primary'), $secure = null); ?>                
        </td>
    </tbody>
    @endforeach
</table

on line <td>{{$exercise->activity_id}}</td> this is just a foreign key for another table named activity_type which has an id and a name, so what I wanted to be shown is the name with this id.

How can I do that?



via Chebli Mohamed

dimanche 29 novembre 2015

Laravel insert FOREIGN KEY in Form Request method

in my application some tables are relationShip and i must be insert FOREIGN KEY to table as User id. i dont have any problem with create new instanse from model and use save() method. but i like to use Form Request method to create and update records,

i get this error and i can not solve that:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a >child row: a foreign key constraint fails (epaypro.merchand_web_service, >CONSTRAINT merchand_web_service_user_id_foreign FOREIGN KEY (user_id) >REFERENCES users (id)) (SQL: insert into merchand_web_service >(updated_at, created_at) values (2015-11-29 11:31:54, 2015-11-29 11:31:54))

this is my model:

namespace app;
use Illuminate\Database\Eloquent\Model;
use Morilog\Jalali\jDate;

class Merchant extends Model
{
    protected $table = 'merchand_web_service';
    protected $fillable = ['customer_key', 'company_name', 'company_logo'];

    /**
     * @return mixed
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

store method on Controller:

public function store(StoreMerchantWebServiceRequest $request)
{
    Merchant::create($request->all());
    return redirect()->route('post.index');
}

StoreMerchantWebServiceRequest class:

class StoreMerchantWebServiceRequest extends Request
{
    public function authorize()
    {
        if (Auth::check()) {
            return true;
        } else
            return false;
    }

    public function forbiddenResponse()
    {
        return Response::make(trans('message.permission_denied'), 403);
    }

    public function rules()
    {
        return [
            'agent_company_name' => 'required',
            'agent_company_logo' => 'mimes:jpg,jpeg,bmp,png|max:300',
        ];
    }
}

My Test (in controller):

public function store(StoreMerchantWebServiceRequest $request)
{
    $order = Merchant::create($request->all());
    $this->user_id = Auth::user()->id;
    $order->save();
    return redirect()->route('post.index');
}



via Chebli Mohamed

Laravel 5 - Redirects in Sub-function

I'm looking for a fix to allow a redirect in a sub-function call, instead of in a controller

I've created the following function & call and it works, with the redirect in the controller instead of my sub function call.

Here is my call to the function checkAccess():

$access = new \App\Library\Access;
if($access->checkAccess($accessList, 'admin-dashboard', 'r')){
    return view('portal.admin.dashboard');
}else{
    return redirect('/');
}

Here is my function:

public function checkAccess($accessList, $element, $permission){
        if(is_array($accessList)){
            foreach($accessList as $access){
                if($access->element == $element && $access->permission == $permission){
                    return true;
                }
            }
        }
        return false;
    }

I have tried replacing the return false; with the redirect and this does not work. It basically just returns true.

And icing on the cake if you know a better way of checking if an object list has parameters w/o having to do a foreach like I am that'd be pretty amazing!



via Chebli Mohamed

Laravel - Homestead issue

I read tutorials on net and try to start using laravel but first I need to install homestead... I do everything like I read but pease help me with this:

MY SCREENSHOOT

why at every command I get 'php' is not reconizes as an internal ... ...

Please help, i'm new to homestead and laravel, before thi question I try almost everything... Why I get this messages at CMD? What is wrong here?



via Chebli Mohamed

Laravel - Deleting Reset Passwords Does nothing

so we are trying to modify the resetpasswords.php file found in /vendor/laravel/src/illuminate/foundation/auth/etc...

So when we modify it locally and test it works fine on my xampp install running windows.

When we modify it on our webserver and test it on linux. It doesn't. No matter the changes to the file nothing happens at all.

We can delete the file and the site will still work even though those functions are not there anymore.

Could use ANY advice on this.

Thank you!



via Chebli Mohamed

redirecting to blade page in laravel gives an error 400

I made a sample php page with composer to load the google api client and it worked fine (gmail api with php) I did the same thing with laravel but I got a problem with

$client->setRedirectUri('http://ift.tt/1lSSQNf');
400. That’s an error.
Error: redirect_uri_mismatch

What to do to make it work



via Chebli Mohamed

Model not found Error - Laravel 5

User Model

class User_Model extends Model
{
    protected $table = "user";
    protected $primaryKey = "UserID";

    public function classes() {
        return $this->hasOne('/app/Models/Classes_Model');
    }
}

Classes Model

class Classes_Model extends Model
{
    protected $table = "classes";
    protected $primaryKey = "ClassID";
}

User Conroller

class UserController extends Controller
{
    public function index()
    {
        //$users = \App\Models\User_Model::all();
        $users = \App\Models\User_Model::find(1)->classes();
        return View("\user\user", array("users" =>  $users));
    }
}

When Controller Action Method runs...I get below error.

Class '/app/Models/Classes_Model' not found

My app structure is below

enter image description here



via Chebli Mohamed

Retrieving the record by Primary Key is not working in Laravel

Table Schema

Create Table User
(
    UserID int,
    FirstName varchar(50)
)

User Model

class User_Model extends Model
{
    protected $table = "user";
}

Below is my code in Laravel 5

$users = \App\Models\User_Model::find(1);

Error Message

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user.id' in 'where clause' (SQL: select * from user where user.id = 1 limit 1)



via Chebli Mohamed

'modelName->save' doesn't reference the name of the tabel in the database correctly in laravel

I am trying to learn laravel, and am following a bunch of tutorials

I am trying to save a object I created inside my model to my database table-contact,but when I do the modelObject->save command in tinker it replaces my table name by contacts instead of contact

Now I know about the snake case plural name system in laravel so I explicitly rename my table in the model as follows :

 protected $table='contact';

But still I get the same error as

`'base table or view not found **laravel.contacts**'` 

Here is my migration :

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

class CreateContactTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('contact', function (Blueprint $table) {
            $table->increments('id');
            $table->text('address');
            $table->string('email');
            $table->timestamps();
        });
    }

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

My model which I create like this:

php artisan make:model contact

The model that was created:

  <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class contact extends Model
{
    protected $table='contact';
}

note :that protected $table='contact' was manually added by me later

Now I create object in tinker as :

$contact=new App\contact
    $contact->address='myaddress'
    $contact->email='myemail'

And then try to save the object to the database using

 $contact->save

But like I've said before laravel tries to save it to contacts instead of contact table

Also,The object '$contact' doesn't reference the default values of timestamp and id in the model as it does in the tutorial may be someone can hint me why..



via Chebli Mohamed

Laravel Validation Passing Blank Input

I have a laravel form to update existing user's information in the database, but if a field in that form is blank, I don't want it to update that record in the database. As it is now, if the field is blank and the form is submitted, it passes that blank input and removes the record in the database.

Below is the function to edit the user's information and then perform the database update. I currently attach the Request::old('...') to the email, but since the validation on that is 'unique:users', it gives the error 'email is taken'.

Thanks,

public function postEdit(Request $request)
{
    $this->validate($request, [
        'email' => 'unique:users|email|max:255',
        'password' => 'min:6',
        'confirm_password' => 'same:password', 
        'about_me' => 'max:500',
    ]);

    Auth::user()->update([


        'email' => $request->input('email'),
        'password' => bcrypt($request->input('password')),
        'confirm_password' => bcrypt($request->input('confirm_password')),
        'about_me' => $request->input('about_me'),
    ]);

    return redirect()->route('profile.edit')->with('info', 'You have updated your profile!');
}



via Chebli Mohamed

Laravel middlware 'only' fires for every route

Whatever I do crud middlware is always fired. However it should only be fired if $crud array is declared and only for routes it contains. However this is not the case it fires every time. Even if I say $crud = []; However if I declare ['only' => ['route1', 'route2']] then it works as expected.

<?php

class BaseController extends Controller
{
    /**
     * Routes which DO NOT load users notifications.
     * @var Array Routes without notifications.
     */
    public $notifications;
    /**
     * Routes which DONT require users account to be configured.
     * @var Array Routes needing configuration.
     */
    public $configured;
    /**
     * Routes which REQUIRE ownership of resource.
     * @var Array CRUD routes.
     */
    public $crud;

    public function __construct()
    {
        $this->middleware('auth', ['except' => $this->routes]);
        $this->middleware('configured', ['except' => $this->configured]);
        $this->middleware('notifications', ['except' => $this->notifications]);
        $this->middleware('crud', ['only' => $this->crud]);
    }
}



via Chebli Mohamed

Laravel 5.1: $errors->all() like response via ajax

Laravel 5.1: When a user is authenticated via regular POST request, an array of all validation errors can be accessed via method $errors->all(). However when a user is authenticated via Ajax request, that property is not available in the returned object. How can I make Validator to return error messages with $errors->all() or in the same structure when authenticating via Ajax request?

public function postLogin(Request $request)
{
    $this->validate($request, [
            $this->loginUsername() => 'required', 'password' => 'required',
        ]);

    $credentials = $this->getCredentials($request);

    if (Auth::attempt($credentials, $request->has('remember'))) {
        return $this->handleUserWasAuthenticated($request, $throttles);
    }
}



via Chebli Mohamed

In Laravel5 there is a link, wich leads back to the former page with inputs

I have two pages. The search and the found.

On the search page there are searching fields. The found gives back the results of searching.

In the template of found page there is a button.

<a class="btn btn-default" href="/search">Back</a>

When I click on the "BACK" button, the input data, wich had been typed in, disappear. How could I make a link, wich retains the input fields?



via Chebli Mohamed

Blade not working (Laravel), why is nothing shown?

Blade not working (Laravel), why is nothing shown?

1.show.blade.php

@extends('book.show')
@section('comment')
    Yuup!
@endsection

http://ift.tt/1HxDSWO

<ul class="cols">
    <li>
       @yield('comment')
    </li>
</ul>



via Chebli Mohamed

How can i run Laravel Queue only once?

I used laravel 5.1 Queue for my background function with async. But i want to run that function for only 1 time. If that function fail, i want to do other process. How can i detect my job is failed or not? Am i doing right or wrong ? What should i change? ps: I'm beginner. I used like this in my controller.

$job = new myjob($var1, $var2);
$this->dispatch($job);
$job->release();
if ($job->attempts() >= 1)
{
    $job->delete();
    //will do other process
}



via Chebli Mohamed

Using middleware for table manipulation laravel 5.1

Currently I am developing a small to middle level application in laravel I came across middleware in laravel, My question is Can i use middleware for making changes in my table for eg, In my application(Canteen Management System), When user orders something from the menu and make request for order then before inserting the order into the model table i want to subtract the order amount from his balance. Reason i am thinking of doing this is because balance attribute is a part of user table and order amount is another part of Order table and i am not being able to develop any data relation between them (but I derive many to one relation between them). So i am not thinking of doing only this thing using data relationship , So that's when i come accross middleware. So help me about this, also Can i use two model in one controller function ?



via Chebli Mohamed

Solr (solarium) connection with laravel 5 in database.php

I use laravel 5 and want to connect to solr 5 with it. I downloaded solarium using composer. But when i try to connect it gives an error.

What works

In my controller (just for now) i did this:

public function __construct()
{

    $config = array(
        'endpoint' => array(
            'localhost' => array(
                'host' => '127.0.0.1',
                'port' => 8983,
                'path' => '/solr/my_solr_instance',
            )
        )
    );

    // create a client instance
    $this->client = new \Solarium\Client($config);
}

Then somewhere else i do this:

$temp = $this->client;

// get a select query instance
$query = $temp->createQuery($temp::QUERY_SELECT);

// this executes the query and returns the result
$resultset = $temp->execute($query);

// display the total number of documents found by solr
echo 'NumFound: '.$resultset->getNumFound();

So far this works. It returns the correct number of 1: NumFound: 1

Problem

Now i changed creating the instance to:

$this->client = new \Solarium\Client(\Config::get('solr')); 

I added this code in the config/database.php file:

'solr' => [

    'endpoint' => [
        'localhost' => [
            'host'     => '127.0.0.1',
            'port'     => 8983,
            'database' => '/solr/my_solr_instance',
        ],
    ],


],

Then, when i run the script again, it says:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Error 404 Not Found</title>
</head>
<body><h2>HTTP ERROR 404</h2>
<p>Problem accessing /solr/select. Reason:
<pre> Not Found</pre></p><hr><i><small>Powered by http://Jetty</small></i><hr/>

</body>
</html>

I would expect that i can set the connection to solr within the database.php file and et the variables of it in the .env file.

How can i solve this issue?



via Chebli Mohamed

laravel 5 overriding postRegister() include needed

I'm overriding the postRegister() method to disable the auto login after registration. Stackoverflow told me to modify this line:

Auth::login($this->create($request->all()));

to:

$user = $this->registrar->create($request->all());

Now I get an error saying:

Undefined property: App\Http\Controllers\Auth\AuthController::$registrar

My includes:

use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Cookie;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Lang;
use Registrar;

What did I need to include?



via Chebli Mohamed

laravel view and data loading

i have a route defined in my route.php file like this:

Route::get('{username}/{search_term}', 'userProfileSearchController@search');

in my controller i retrieve the user model from db by the username and then performing a search query for finding the results based on the passed term then i redirect the to a view like below:

return view('profile', compact('result'));

but the problem is it doesn't redirect to view properly instead of redirecting to profile view with just the result variable i gave it redirects like this http://ift.tt/1TkQEJu and my stylesheets and scripts doesn't load on page because of the wrong url laravel is giving!
so they trying to load in page with this url:

http://ift.tt/1IhuQNY



via Chebli Mohamed

Laravel - How to open the third tab in a page

I have 4 tabs in my user view.

When the page loads, how do I make my view display the third tab as active?

I am using Bootstrap :-

<div>
<ul class="nav nav-tabs" role="tablist">
   <li role="presentation" class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">Home</a></li>
   <li role="presentation"><a href="#profile" aria-controls="profile" role="tab" data-toggle="tab">Profile</a></li>
   <li role="presentation"><a href="#messages" aria-controls="messages" role="tab" data-toggle="tab">Messages</a></li>
   <li role="presentation"><a href="#settings" aria-controls="settings" role="tab" data-toggle="tab">Settings</a></li>
 </ul>


<div class="tab-content">
   <div role="tabpanel" class="tab-pane active" id="home">Home</div>
   <div role="tabpanel" class="tab-pane" id="profile">Profile</div>
   <div role="tabpanel" class="tab-pane" id="messages">Messages</div>
   <div role="tabpanel" class="tab-pane" id="settings">Settings</div>
</div>

</div>



via Chebli Mohamed

TokenMismatchException in VerifyCsrfToken.php line 53: in laravel 5.1

Below is my form code

 <div class="row">
    <div class="form-group col-sm-12">   
    <input type="text" name="name" class="form-control" id="name" placeholder="Enter name ">
    </div>
</div>
<div class="row">
    <div class="form-group col-sm-12">   
    <input type="email" name="email" class="form-control" id="email" placeholder="Enter email ">
    </div>
</div>
<div class="row">
    <div class="form-group col-sm-12">
    <input type="password" name="password" class="form-control" id="pwd" placeholder="Enter password">
    </div>
</div>
<div class="row">
    <div class="form-group col-sm-12">
    <input type="password" class="form-control" id="pwd" placeholder="Re-enter password">
    </div>

  <div class="row">
  <div class="col-sm-6 ">

  <input type="submit" class="btn btn-info" value="SIGNUP">
  </div>

  </div>

    </form>

After submitting form it shows TokenMismatchException in VerifyCsrfToken.php line 53: I am completely get frustrated due to this errror. I also used token in the form and also tried to clear cache but still facing same problem What will be the problem? Please help me. Thank You in advance



via Chebli Mohamed

samedi 28 novembre 2015

What does $app['files'] do in Laravel 5

I came across this code

$app['files] in a laravel package.

I am just wondering what it does in laravel.

Thanks



via Chebli Mohamed

Call to undefined function App\belongsToMany [Laravel]

The error i am getting is "Call to undefined function App\belongsToMany".

This is one of the two models that is used for the relationship:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Review extends Model
{
protected $table = "reviews";

protected $fillable = [ 'user_id','email','review'];

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

public function votes()
{
    return $this->belongsToMany('App\User')->withPivot('vote')->withTimestamps();
}

public function categories()
{
    return $this-belongsToMany('Category','category_review','review_id','category_id')->withTimestamps();
}

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

}

My other model :

<?php

 namespace App;

 use Illuminate\Database\Eloquent\Model;

 class Category extends Model
 {
public function reviews()
{
    return $this->belongsToMany('App\Review','category_review','category_id','review_id')->withTimestamps();
}

public function children()
{
    return $this->hasMany('App\Category','parent_id');
}

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

}

The problem is, i can run the App\Category::find(1)->reviews; but, i can't run App\Review::find(1)->categories; It says "Call to undefined function App\BelongsToMany"



via Chebli Mohamed

Advanced Select statement (Laravel)

In the Products table i have the store_id column which connects the product with the store.

In my APIController which i use with Angular i have this return statement. I am returning a collection of products.

return Product::where('category_id', $category->id)->select(array('id',
                                                                        'name',
                                                                        'newprice',
                                                                        'image',
                                                                        'store_id',
                                                                        'link'))->paginate(20);

My problem is that instead of returning the store_id(from the products table) i want to return the store name, which is NOT stored in the same table. Is there any way to do that? Is my only option the use of JOIN?



via Chebli Mohamed

Laravel5 : MethodNotAllowedHttpException

When I'm trying to post something with the form it gives this Error.

This is my route:

// CONTESTS
Route::get('contests', 'ContestsController@index'); <br>
Route::get('applycontest', 'ApplyContestController@index'); <br>
    // ->post <br>
    Route::post('applycontest', 'ContestsController@store'); <br>

This is my view:

@extends('app')
@if (Auth::check())
@section('content')
    <div class="contestbanner">
          <p class="contestbanner-heading">A LITTLE CONTEST NEVER HURT NOBODY</p>
    </div>
    <div class="apply">
        <h1>Apply for our contest!</h1>

        {!! Form::open(array('url' => 'contests', 'files' => true)) !!}
            {!! Form::label('title', 'Title:') !!}
            {!! form::text('title', null, ['class' => 'form-control', 'autofocus']) !!}

            {!! Form::label('desc', 'Description: ') !!}
            {!! form::textarea('desc', null, ['class' => 'form-control']) !!}

            {!! Form::label('image', 'Add an image') !!}
            {!! form::file('image', null, ['class' => 'form-control'])!!}

            <br/>

            {!! Form::Submit('Add your work', ['class' => 'btn btn-primary form-control']) !!}

        {!! Form::close() !!}
    </div>
@else 
    @section('message')
        @include('includes.anonymous')
    @stop
@endif

    <div class="back">
        <a class="back-button" href="contests">Go back</a>
    </div>

@stop           
@stop

This is the controller:

http://ift.tt/1IgUMJn

Thanks in advance!



via Chebli Mohamed

Laravel 5: All tableseeders get seeded and 1 tableseeder doesn't

I'm trying to get my ContesttableSeeder to show on my page and terminal but they won't appear.

This is my ContestableSeeder
This is my terminal and as you can see, the table has been created: create_contests_table but the seeding doesn't show. I tried a couple of times, sorry for the mess :)

Does anybody know a solution? Thanks in advance!



via Chebli Mohamed

Modify input in laravel middleware

Some service makes HTTP request to my site and passes some input. This input has a little bit wrong structure for me, so I'm trying to modify it.

I made a middleware and attached this middleware to my route. The handle method looks like this:

public function handle($request, Closure $next)
{
    $input = $request->all();

    // Input modification

    $request->replace($input);
    \Log::info($request->all()); // Shows modified request

    return $next($request);
}

However in my controller I got old input. Also I'm a little bit confused since I also use FormRequest, and as I realize these two requests are different entities. Then how can I modify the input in the middleware?



via Chebli Mohamed

HTML minification interferes with Intervention package

I'm implementing the Intervention package to dynamically resize images in my site. It's working quite well and I'm happy with it. Here's an example of how I do it:

Route::get('images/ads/{width}-{ad_image}-{permalink}.{format}', function($width, $image, $permalink, $format)
{
    $img = Image::make($image->path)
        ->resize($width, null, function($constraint){
            $constraint->aspectRatio();
        });
    return $img->response($format);
});

Recently, I thought of making my site load faster by auto-compressing my views via a middleware:

class HTMLminify
{
    public function handle($request, Closure $next) {
        $response = $next($request);
        $content = $response->getContent();

        $search = array(
            '/\>[^\S ]+/s', // strip whitespaces after tags, except space
            '/[^\S ]+\</s', // strip whitespaces before tags, except space
            '/(\s)+/s'       // shorten multiple whitespace sequences
        );

        $replace = array(
            '>',
            '<',
            '\\1'
        );

        $buffer = preg_replace($search, $replace, $content);
        return $response->setContent($buffer);
    }
}

Then came the nightmare. Browsers report that the images processed by Intervention are now "truncated" and won't display. Turning off the middleware displays the images without a problem.

As far as I can see from the HTMLminify class' codes is that it modifies the output generated from the views and removes the whitespaces and don't see any reason how it could interfere with images.

Any ideas, guys?

Thanks in advanced.



via Chebli Mohamed

Strange Exception telling the file does not exist or is not readable in Laravel 5.1

I'm getting reports with exceptions like these:

exception 'InvalidArgumentException' with message 'The file "/var/www/http://ift.tt/1MWBYvF" does not exist or is not readable.' in /var/www/http://ift.tt/1RdcwHL
Stack trace:
#0 /var/www/http://san
...

As you can see it's weird that it's trying to access that does not exist for sure /var/www/http://sandbox4b5ace....

The type of Exception may change. I've put here the full dump of it.

I've no clue of why is this throwing this Exception, the only thing I recognize is the file path has as string taken from the mailgun api sandbox credentials. So, I'ts strange.

Any light on this is welcome.

The full project is here



via Chebli Mohamed

Laravel 5 deployment getting internal server error

Leravel 5 deployment getting :

Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request

My file structure:

|
|-pub                           -> from laravel folder public
|-my_apps
     |- my_first_app            -> all other files from laravel project
           |- app
           |- bootstrap
           |- config
           |- database
           |- resources
           |- storage
           |- ...

I have set storage folder permission to be:

user::rwx

group::rwx

other::rwx

This is my .htaccess file in directory /pub

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On
    RewriteBase /  <-------- I added this line

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

I also change path in \pub\index.php

<?php

//updated path
require __DIR__.'/../my_apps/my_first_app/bootstrap/autoload.php';

//updated path
$app = require_once __DIR__.'/../my_apps/my_first_app/bootstrap/app.php';

$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);

$response = $kernel->handle(
    $request = Illuminate\Http\Request::capture()
);

$response->send();

$kernel->terminate($request, $response);



via Chebli Mohamed

why do i have to run "composer dump-autoload" command to make migration work in laravel

i have built some migration classes in my application to create the tables i need , but i keep getting errors when i run the command:

composer dump-autoload

then it works again as expected , am i doing something wrong that generates this error or this is a normal behaviour in migration ?

Below is the error that i get when running the migration process:

  [Symfony\Component\Debug\Exception\FatalErrorException]  
  Class 'CreateVideoStatusTable' not found  



via Chebli Mohamed

Laravel summernote HTML output

I'm using Laravel 5 and Summernote editor, with some issues. I have a page where I can write an article and then save it which works fine. But when i try to edit the article, I get the html code in the textarea instead of getting the formatted content.

in add-article.blade.php:

{!! Form::textarea('body','',['name'=>'body','id'=>'body','class' => 'form-control']) !!}

in edit-article.blade.php:

{!! Form::textarea('body',$article->body,['name'=>'body','id'=>'body','class' => 'form-control']) !!}



via Chebli Mohamed

Laravel 5 : Client error 400 after user click cancel authorize the facebook permission

i'm currently facing some issue regarding facebook login. I've integrated facebook login with my application, the only problem is that the error 400 happens when user click cancel during the facebook aauthorization. Anyone have some clue for it?

Note : facebook login is working fine, problem happens when new user click sign up with facebook, but cancel the authorization.

this are the call back url from facebook. http://localhost/login/facebookCallback?error=access_denied&error_code=200&error_description=Permissions+error&error_reason=user_denied&state=gMwDR0TATB6Kt5IwIkbFCA5LOypOYSJjhK8Mz0fj#=

my route

Route::get('login/facebookLogin', 'ProfileController@redirectToProvider');
Route::get('login/facebookCallback', 'ProfileController@handleProviderCallback');
Route::get('logout/facebookLogout', 'ProfileController@facebookLogout');

my controller :

public function redirectToProvider(){
        return Socialize::with('facebook')->redirect();
    }

    public function handleProviderCallback(Request $request)
    {
        $user = Socialize::with('facebook')->user();
        $datetime = new \DateTime();
        $datetime->format('Y-m-d H:i:s');
        $datetime->getTimestamp();
        $data = User::where('facebook_id', '=', $user->getId())->first();

        if (is_null($data)) {
            $data = new User;
            $data->country_id = 1; // default to malaysia
            $data->user_name = $user->getname();
            $data->facebook_id = $user->getId();
            $data->steam_link = null;
            $data->password = null;
            $data->extra_information = null;
            $data->remember_token = null;
            $data->email = $user->getEmail();
            $data->status_id = 1;
            $data->is_verified = 1; // verified
            $data->user_type_id = 2; // normal user
            $data->account_status_id = 2; // active
            $data->created_at = $datetime;
            $data->updated_at = $datetime;
            $data->save();

            $UserLogin = User::where('facebook_id', '=', $user->getId())->first();
            Auth::login($UserLogin, true);
            return Redirect::to('profile/profileSetting')->with('data', $data);
        } else {
            $data->user_name = $user->getname();
            $data->updated_at = $datetime;
            $data->save();

            $UserLogin = User::where('facebook_id', '=', $user->getId())->first();
            Auth::login($UserLogin, true);
            return Redirect::to('/');
        }
    }

error : ClientException in Middleware.php line 69: Client error: 400



via Chebli Mohamed

php artisan migrate isn't working

When I try to connect to my database i get this error

[PDOException]                                                               
SQLSTATE[HY000] [1045] Access denied for user 'loom'@'localhost' (using password: YES)

all my credentials are correct and when i change things up i get this error :

[PDOException]                                        
SQLSTATE[HY000] [1049] Unknown database 'loomcoding'

Can anyone help me sort this out please

my .env file

APP_ENV=local
APP_DEBUG=true
APP_KEY=xxxx

DB_HOST=localhost
DB_DATABASE=cl20-loom
DB_USERNAME=loom
DB_PASSWORD=xxxx

CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

my database.php file :

'mysql' => [
        'driver'    => 'mysql',
        'host'      => 'localhost',
        'database'  => 'cl-loom',
        'username'  => 'loom',
        'password'  => '••••',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],



via Chebli Mohamed

Laravel 5.1 registration form with new field

I am creating referal system so..

    // Registration routes...
Route::get('auth/register/{id}', 'Auth\AuthController@getRegister');
Route::post('auth/register', 'Auth\AuthController@postRegister');

and my RegisterUser.php is changed to

public function getRegister($id)
{
    return view('auth.register')->withName($id);
}

and my blade look like

<div class="form-group">
    <label class="col-md-4 control-label">Company</label>
          <div class="col-md-6">
              <input type="text" class="form-control" name="company" value="{{ old('company') }}" readonly  disabled>
           </div>
</div>

and the value="{{ old('company') }}" is making the problem .... When is like that is working ... but I want the value to be value="{{$name}}" given from return view('auth.register')->withName($id); ..... so when i go to route auth/register/something in the input fuild I have got the 'something' so it is working but I have the error code "Undefined index: company". When I remove the value at all it is working but I need this value. Any suggestion will be helpfull. Thank you



via Chebli Mohamed

getting error while declaring wildcard into sleeping owl admin panel for laravel

I have added this menu into menu.php

Admin::menu()->url('user')->label('Users')->icon('fa-users')->uses('\SleepingOwl\Admin\Controllers\UsersController@index');

And its working ok, Now i want single user listing, So for that i want URL like this admin/user/{id}. What i tried is

Admin::menu()->url('user/{id}')->hidden()->uses('\SleepingOwl\Admin\Controllers\UsersController@getuser');

Not working,If i remove wildcard then it will work.



via Chebli Mohamed

Laravel 5 Eloquent: do not contain all fields after saving

for example there are 4 files in table users:
name | avatar | created_at | updated_at
when user model is saved with only name:

public function reg(){
  $user = new User; 
  $user->name = 'aName';    
  $user->save();
  return response()->json($user);
}

then I get the response json:

{
  "id":1;
  "name":"aName",
  "created_at":"xxxxxxxx",
  "updated_at":"xxxxxxxx"
}

there is no filed avatar, I want the response also contains avatar filed even I did not set value for it.



via Chebli Mohamed

Laravel simple router controller@action get NotFoundHttpException Error

i'm below code is my simple route to use Controller action:

Route::get('/CheckCustomerTransactionPayment', 'PaymentTransactionController@check');

and this is my controller class:

namespace App\Http\Controllers;

use App\CustomerTransactions;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Support\Facades\Log;
use Payment\Payment;

class PaymentTransactionController extends Controller
{
    public function check(Request $request)
    {
        dd($request->all());
    }
}

i get this error:

NotFoundHttpException in RouteCollection.php line 161:

URL to check that:

http://localhost/project/public/CheckCustomerTransactionPayment/112323



via Chebli Mohamed

Reducing code complexity and optimizing code structure

I have an application whose reporting module has been badly coded. It is a standard Laravel model which holds a collection of reporting methods that each contain a specific database query. To use the reporting module in the application, the end-user selects from a pre-determined set of filters to generate a requested report. Many reports share common functionality and do the majority of high-level logic within the database layer.

I have an ongoing goal of reducing code complexity and optimizing code structure. How can I leverage common OOP design patterns to ensure altering the code in any given report does not negatively affect the other reports?

Also, the reporting module is relatively static in definition and unlikely to change over time. The majority of reports generated by the application involve nested sub-queries as well as standard grouping & filtering options. From a solution architecture perspective (without looking too much into DB structure or table indices) what are the recommendations for scaling the report functionality to ensure optimized performance?



via Chebli Mohamed

vendredi 27 novembre 2015

How to show a fancy 404 page and recording/emailing all exception to Admin

I am on Laravel 5.1.

Whenever there is an exception, Laravel usually shows an exception on the page. I'd like to add a custom 404 page with a human readable error report and email an admin with the entire error dump. I would also like to have the email nicely formatted in HTML (like on the error page).

How can I do this?



via Chebli Mohamed

Larevel - Define path variable

how do i define path variable in laravel? For example, i have a webserver path http://ift.tt/1NTLJLa

in my html i will

   <img style="width: 100%;padding:1px;border: 2px solid #555" src="http://ift.tt/1HueJMO{{ $data->ap_thread_created_by}}/{{ $data->image_path }}">

but i wish to get the path in my config or somewhere else.. instead of hardcoding the path.



via Chebli Mohamed

Update with Laravel and ajax

Hello everybody iam new to laravel and i hope you will help me to solve this problem. I want to update a particular column conditions, 1 to 0 and 0 to 1 when user click the link with Ajax. I have column named status which can have value 1 or 0,according to user click the link value gets updated.

I have two route

 Route::get('/logo/updateY/{id}', [ 'uses'=> 'Backend\Logo\LogoController@updateYesStatus', 'permission'=> 'update' ]);
 Route::get('/logo/updateN/{id}', [ 'uses'=> 'Backend\Logo\LogoController@updateNoStatus', 'permission'=> 'update' ]);

controller

public function updateYesStatus($id)
  {
     $logoStatus = Logo::findOrFail($id);
     $logoStatus->update(['status'=>'1']);
     return redirect::to('administrator/logo/view');

  }
  public function updateNoStatus($id)
  {
     $logoStatus = Logo::findOrFail($id);
     $logoStatus->update(['status'=>'0']);
     return redirect::to('administrator/logo/view');

  }

view:

@if($logo->status== 1)
  <td ><a  href="{{url('/administrator/logo/updateN',[$logo->id])}}" class="label label-success userStatus"id="{{$logo->id}}">Displayed</a></td>
  @else
 <td ><a href="{{url('/administrator/logo/updateY',[$logo->id])}}" class="label label-danger userStatus" id="{{$logo->id}}">Hidden</a></td>
   @endif</td>





<script type="text/javascript">
    $(document).on('click','.userStatus',function(){
        var id = $(this).attr('id');
        $.ajax({
            data:{ id=id, _token: '{!! crfs_toekn() !!}'},
            url: '',
            type: 'POST',
            dataType: 'json'

            success:function()
            {

            }
       });
    });


</script>



via Chebli Mohamed

Eloquent User Where Clause with Entrust Library

I'm trying to select all users for a company. But only users who has "admin" role status (Entrust, etc.).

User::where('company_id', Auth::user()->company_id)->hasRole('admin')->get();

The above is throwing an error. Left a bit lost on how to run such a query. Where am I going wrong with this? Very little documentation on Entrust.



via Chebli Mohamed

error of foreach with empty array

I'm working in Laravel 5 using Blade as motor of templates. I'm passing an array from the controller to the view, and I noticed that when I loop on it using the foreach clausule and the array is empty it gives error, exactly this:

Invalid argument supplied for foreach() 

I had the same error in the controller and I fix it temporaly making:

if(count($student)!=0)

I said temporaly because I don't think it this the best way to do it. But know, in the view I have the same error. So, it's normal? how could I fix it in a better way? why when the array is empty the foreach clausule gives that error?



via Chebli Mohamed

Increment Php Carbon Date in for loop with Laravel

i try to increment carbon Date in for loop as the following

for($x =0 ; $x < count($ms); $x ++) {

 $msh= MaintenanceServiceNotifications::where('main_service_id',$ms[$x]->id)->where('status','done')->orderBy('created_at','desc')->first();

  if(Carbon::now() > $msh->created_at->addMinutes($ms[$x]->notification_period*2) ) {

   for ($i = 0; $i < sizeof($customersNot)-1; $i++) {

   //here i need to get created_at and 30 minutes for it     
   $created_at[$i] = $msh->created_at->addMinutes($ms[$x]->notification_period);

   MaintenanceServiceNotifications::create([
              'main_service_id' => $ms[$x]->id, 'user_id' => Auth::user()->id,
               not_name => 'some text', 'created_at' => $created_at[$i]
            ]);
            }
        }
     }

i need to increment date in each for loop and pass it to created_at for example

in first loop 2015-11-27 23:00:00 then creteat_at => 2015-11-27 23:00:00

in second loop 2015-11-27 23:30:00 then created_at =>2015-11-27 23:30:00

Any Suggestions,Thanks



via Chebli Mohamed

Loop through an array and print out a template for each iteration

I don't know how to do this and i hope i can get some tips from you.

I get an array with some data from a function. This function is defined in my Controller (HomeController). And the array is built as following:

Array
(
[1] => Array
    (
        [message] => xxx
        [name] => yyy
    )

[2] => Array
    (
        [message] => xxx
        [name] => yyy
    )

[3] => Array
    (
        [message] => xxx
        [name] => yyy
    )

[4] => Array
    (
        [message] => xxx
        [name] => yyy
    )

) 

Now i got this data in my Controller. Next i want to show this data on my view. I want to loop through each data and render it out.

Should i return the array to my view and loop in my view through the array? Or what is the best method for this?

And additionally i got another question. I dont want to just render it out inside the loop. I thought about something like a template. Is it possible to define a template and on every iteration i give the informations from the array to my defined template and then render it out?

The template may look something like this:

<div class="box">
    <h1> $data["name"] </h1>
    <p> $data["message"] </p>
</div>

And then the loop maybe like this:

foreach(...) {
    // the template is rendered here with the array data
    {{ @template($data) }}
}

Thanks for any help!



via Chebli Mohamed

array_add method In laravel

i try to use array_add method to add new element to array in for loop

 public function getNotArray() {   

   // looping over $service Object
for($x = 0; $x < count($service);$x++) {

  $firstService[$x] = $service[$x]->first_date_for_service;

        while (Carbon::now() > $firstService[$x]) {

            $firstService[$x]->addMinutes($service[$x]->notification_period);

    if($firstService[$x] < Carbon::now() && $firstService[$x] > $service[$x]->serviceHistory->where('status','done')->max('created_at')) {

      $arr[] = array_add($service[$x],'notificationDate',date($firstService[$x]));

            }
        }

    }
    return  $arr;
   }  

The above script working well ,but return notificationDate fixed value when loop over $arr

i need to get notificationDate according for value that $firstService[$x] carries in each loop

Any Suggestions,Thanks



via Chebli Mohamed

Laravel 5 Password Reset Email Not Being Sent

I am trying to implement a password reset on my Laravel 5.1 app. I have followed the docs (http://ift.tt/1OzaSjA) to get this working. However whenever I click on my 'reset password' button on my /password/email/ no email is ever sent.

I have intentionally entered incorrect emails and I am getting the appropriate error however when I enter a correct email no email is sent and I get no type of message or any emails.

I have looked at my database and it does looks as though a password reset token being created, just no email is sent.

My email configuration is working properly as other parts of my application sends email properly, only this one section is not sending the emails. Any help will be appreciated as I do not what else to check.

Michael

routes.php: `

// Password reset link request routes...
Route::get('password/email', ['as' => 'password/email', 'uses' => 'Auth\PasswordController@getEmail']);
Route::post('password/email', 'Auth\PasswordController@postEmail');

    // Password reset routes...
    Route::get('password/reset/{token}', 'Auth\PasswordController@getReset');
    Route::post('password/reset', 'Auth\PasswordController@postReset');

password.blade.php:

<form id="contact-form" class="contact-section" method="POST" action="/password/email">
            <input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
            <span class="pre-input"><i class="fa fa-envelope-o"></i></span>
            <input class="name plain buffer" type="email" name="email" placeholder="Email" value="{{ old('email') }}">
            <input id="send" class="plain button yellow" type="submit" value="Reset Password">
              @foreach($errors->all() as $error)
              <font size="3" color="red">{{ $error }}</font>
              @endforeach

          </form> 



via Chebli Mohamed

Laravel 5.1 suggested relationship setup

I am building a timesheet system and have setup a model for timesheets. Timesheet can have many rows - for example when I add a timesheet, I can add many days (rows) to the timesheet.

I want to be able to sync rows when a timesheet gets saved. For example, new rows will be added to the database, missing rows from the given array will be removed from the database.

I understand I can use sync method which works like this, however, I do not think I need a belongsToMany relationship. Currently I have my row relationship setup as a hasMany. The timesheet model looks like this:

<?php

namespace App\Models\Timesheet;

use Illuminate\Database\Eloquent\Model;

class Timesheet extends Model
{    
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'timesheet';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['user_id', 'week', 'year', 'token', 'total_hours'];

    /**
     * Define that we want to include timestamps.
     *
     * @var boolean
     */
    public $timestamps = true;

    /**
     * Boot the model.
     *
     */
    public static function boot()
    {
        parent::boot();

        static::deleting(function($timesheet)
        {
            $timesheet->row()->delete();
        });
    }

    /**
     * The rows that belong to the timesheet.
     *
     * @return Object
     */
    public function row()
    {
        return $this->hasMany('App\Models\Timesheet\RowTimesheet');
    }

}

The row_timesheet model looks like this:

namespace App\Models\Timesheet;

use Illuminate\Database\Eloquent\Model;

class RowTimesheet extends Model
{    
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'row_timesheet';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['timesheet_id', 'activity_category', 'description', 'eri_number', 'ewn_number'];

    /**
     * Define that we want to include timestamps.
     *
     * @var boolean
     */
    public $timestamps = true;

What do I need to do in order to make something like this work:

$this->timesheet->find($id)->row()->sync($data);

Thanks in advance.



via Chebli Mohamed

PHP inherit global variable in Anonymous functions

I can't use variable $data in Anonymous functions:

$data = array(...);
Excel::create('Filename',function($excel){
  foreach($data as $v){
     //...
  }
});

I get error: "Undefined variable: $data"

Also:

 $data = array(...);
 Excel::create('Filename',function($excel){
   global $data;
   foreach($data as $v){
      //...
   }
 });

I get error "Invalid argument supplied for foreach()"

How I can use $data in Anonymous function?



via Chebli Mohamed

PHP -> NumberFormatter not working

I have php file test.php:

use App\Classes\test_class;

$xml = new DOMDocument( "1.0", "ISO-8859-15" );
echo 'DOMDocument-ok<br/>';

$formatter = new NumberFormatter('en_US', NumberFormatter::DECIMAL);
echo 'NumberFormatter-ok<br/>';
new test_class();

And test_class.php:

class test_class{

    public function __construct()
    {
        $xml = new \DOMDocument( "1.0", "ISO-8859-15" );
        echo 'DOMDocument-ok<br/>';

        $formatter = new \NumberFormatter('en_US', \NumberFormatter::DECIMAL);
        echo 'NumberFormatter-ok<br/>';
    }

}

When I run this code output is:

DOMDocument-ok
NumberFormatter-ok
DOMDocument-ok
NumberFormatter-ok

But in plugin "sebastian/money" when I use plugin I get this error "Symfony \ Component \ Debug \ Exception \ FatalErrorException (E_UNKNOWN) HELP Class 'NumberFormatter' not found"

For code:

<?php
namespace SebastianBergmann\Money;

use NumberFormatter;

class IntlFormatter implements Formatter
{
    private $numberFormatter;
    public function __construct($locale)
    {
        $this->numberFormatter = new NumberFormatter(
            $locale,
            NumberFormatter::CURRENCY
        );
    }

For line :

$this->numberFormatter = new NumberFormatter(
            $locale,
            NumberFormatter::CURRENCY
        );

EDITED:

Apparently NumberFormatter not working inside all Laravel app, but I don't know why, can someone help?



via Chebli Mohamed

Laravel 5.1 firstOrNew with relationships

How can I use firstOrNew method with Laravel relationships.

I have the following relationship:

/**
 * The rows that belong to the timesheet.
 *
 * @return Object
 */
public function rowTimesheet()
{
    return $this->hasMany('App\Models\Timesheet\RowTimesheet');
}

I am trying to create a new row for the timesheet in the database using the following. I don't get any errors, but the row doesn't get inserted.

Any ideas?

/**
 * Create timesheet rows.
 *
 * @param $id
 * @param $row
 */
public function createTimesheetRow($id, $row) 
{
    return $this->timesheet->find($id)->rowTimesheet()->firstOrNew($row);
}



via Chebli Mohamed

Laravel 5.1: Get ID from firstOrNew method

I have the following function which creates a new record in the database if one doesn't already exists - if one exists, it updates it. The problem is that it returns true and therefore I can't get the ID of the inserted or updated record.

/**
 * Save timesheet.
 *
 * @param $token
 * @param $data
 */
public function saveTimesheet($token, $data) 
{
    return $this->timesheet->firstOrNew($token)->fill($data)->save();
}



via Chebli Mohamed

Returning the custom validation method parameter in error message

I have a created a custom validation function along with a custom error message for it. How can I show the value "1000" in my error message?

  // in my request file
  function rules() 
  {
    return [
        'my_field' => 'myValidator:1000',
    ];    
  }

  // in my custom validator file
  public function validateMyValidator($attribute, $value, $parameters)
  {
      return true;
  }

  // in resources/lang/eng/validation.php
  'custom' => [
    'my_field' => [
        'my_validator' => 'Value must be 1000',
    ],
  ]



via Chebli Mohamed

jeudi 26 novembre 2015

Laravel relation with 2 different models in same relation

I'm trying to do this in Laravel5: I have model order_item with attributes: order_item_id, item_id and item_type. Item_id is ID of related item. And item_type is "product" or "service". Order_item has function item() where I want to put relation with product or service in dependence on item_type. For example:

order_item: item_id = 1; item_type = 'product' => item() should return model App\Models\Product

if order_item is like this:

`order_item: item_id = 1; item_type = 'service' => item() should return model App\Models\Service`

Here is example of my model:

<?php namespace App\Models;

use App\Models\Model;

class OrderItem extends Model
{

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'orders_items';

    protected $primaryKey = 'order_item_id';

    /**
     * The attributes that are mass assignable.
     *
     *  item_type: product | service
     *
     * @var array
     */
    protected $fillable = ['order_item_id', 'order_id', 'item_id', 'item_type'];



    public function order() {
        return $this->hasOne('App\Models\Order', 'order_id', 'order_id');
    }

    public function item() {
    }

}



via Chebli Mohamed

convert to nested format php

I just want some help in displaying the correct structure of the image data below. Basically what i want is to display it in nested form. From the data below, I would like it to display like this:

  • Engel (parent which parent_id = 0)
    • Chest Fridge - Freezers
      • Small Engel
      • digital platinum
    • Upright Fridge
      • Built-in fridge
    • Fridge Accessories
      • Blankets
      • Carry handles

enter image description here

I hope anyone can help me. Im using php fyi.



via Chebli Mohamed

laravel 5.1 auth.login event triggered twice

Im building my app with laravel, and i create logger that log user login to mysql database, i used built in event auth.login, and then this is my code in class EventServiceProvider

This is my EventServiceProvider.php

protected $listen = [
    'App\Events\UserFailedLoggedInEvent' => [
        'App\Listeners\UserFailedLogginLogger',
    ],

];

/**
 * Register any other events for your application.
 *
 * @param  \Illuminate\Contracts\Events\Dispatcher  $events
 * @return void
 */
public function boot(DispatcherContract $events)
{
    parent::boot($events);

    $events->listen('votee.*', function($user, $voteable, $counter){
        $voteable->vote_down = $counter->down;
        $voteable->vote_up = $counter->up;
        $voteable->save();
    });

    $events->listen('mural.comment.add', function($comment, $content, $author, $room){
        $content->increment('comment');
    });

    $events->listen('mural.comment.remove', function($comment, $user){
        $comment->commentable->decrement('comment');
    });

    $events->listen('auth.logout', 'App\Listeners\UserLogoutLogger@handle');

    $events->listen('auth.login', 'App\Listeners\UserLoginLogger@handle');

}

}

And this is my App\Listeners\UserLoginLogger, i use spatie/activitylog

public function handle()
{
    Activity::log("Logged In");
}

but it will save to the database two login activity.



via Chebli Mohamed

How to create a user in seeder in Laravel - Password not working?

I am trying to create a seeder in laravel. So far I have the following:

User::create([
      'name' => 'John Smith'   
      'email' => 'john@example.com',
      'password' => 'letmein',
]);

However this does not seem to work when logging in as this user using laravel's authentication service. What am I doing wrong?



via Chebli Mohamed

Laravel 5 - creating two tables during registration

In my database design, I have two tables, People & Auth. The Auth table holds authentication information and the person_id while the People table holds all other information (name, address, etc). There is a one-to-one relationship between the tables as seen in the models below.

The reason I have separated the data into two tables is because in my application, I will have many people who do not have authentication capabilities (customers to the user).

App/Auth.php

   class Auth extends Model implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract
    {
        use Authenticatable, Authorizable, CanResetPassword;

        public function person() {
            $this->belongsTo('Person');
        }
    }

App/Person.php

class Person extends Model
{
    public function auth() {
        $this->hasOne('Auth');
    }
}

In my AuthController::create() method, I am attempting to populate both models with the user supplied information like this:

protected function create(Request $request)
    {
        $person = \App\Person::create($request->all());

        $auth = new \App\Auth;
        $auth->fill($request->all());
        $auth->person_id = $person->id;
        $auth->save();

        return $person;
    }

In my application, I would like to authorize a user and pass a $user object as the authenticated person to subsequent routes. Am I doing this correctly? Is this the best way? There's cookies and bonus points if you can also explain how to retrieve the $user object after authentication...Auth table data is not needed in the $user object.



via Chebli Mohamed

Laravel header CORS

Problem

When I go to the url http://api.example.com through my browser (Chrome), it shows me this, with correct headers (notice the Access-Control-Allow-Origin field)

enter image description here

But when I do a post request to http://api.example.com from http://test.example.com, it shows me this enter image description here

And the console shows me

XMLHttpRequest cannot load http://ift.tt/1T8hGTP. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://test.example.dev' is therefore not allowed access. The response had HTTP status code 500.

What I did

I'm using the framework Laravel 5 and I followed this tutorial to add header to responses. I copied exactly the piece of code of the tutorial. What is still wrong here ?

Where



via Chebli Mohamed

Laravel 5 jenssegers MongoDB and Fire / Listener fails on undefined builder::fire

Anyone out here used the Jenssegers MongoDB in Laravel that have succesfully setup events and listeners with it?

I have an event and listener set up with php artisan, and when I add a Fire to execute an event I get the following error:

BadMethodCallException in Builder.php line 2071:
Call to undefined method Jenssegers\Mongodb\Query\Builder::fire()

This is my entire stack trace:

in Builder.php line 2071
at Builder->__call('fire', array(object(TicketHasBeenBought))) in Builder.php line 1058
at Builder->__call('fire', array(object(TicketHasBeenBought)))
at Builder->fire(object(TicketHasBeenBought))
at call_user_func_array(array(object(Builder), 'fire'), array(object(TicketHasBeenBought))) in Builder.php line 943
at Builder->__call('fire', array(object(TicketHasBeenBought)))
at Builder->fire(object(TicketHasBeenBought))
at call_user_func_array(array(object(Builder), 'fire'), array(object(TicketHasBeenBought))) in Model.php line 3482
at Model->__call('fire', array(object(TicketHasBeenBought))) in Model.php line 537
at Model->__call('fire', array(object(TicketHasBeenBought)))
at Event->fire(object(TicketHasBeenBought))
at call_user_func_array(array(object(Event), 'fire'), array(object(TicketHasBeenBought))) in Model.php line 3496
at Model::__callStatic('fire', array(object(TicketHasBeenBought))) in Orders.php line 227
at Event::fire(object(TicketHasBeenBought)) in Orders.php line 227
at Orders->store(object(Request))
at call_user_func_array(array(object(Orders), 'store'), array(object(Request))) in Controller.php line 256
at Controller->callAction('store', array(object(Request))) in ControllerDispatcher.php line 164
at ControllerDispatcher->call(object(Orders), object(Route), 'store') 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(Orders), object(Route), object(Request), 'store') in ControllerDispatcher.php line 69
at ControllerDispatcher->dispatch(object(Route), object(Request), 'App\Http\Controllers\Orders\Orders', 'store') in Route.php line 203
at Route->runWithCustomDispatcher(object(Request)) in Route.php line 134
at Route->run(object(Request)) in Router.php line 712
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 714
at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 679
at Router->dispatchToRoute(object(Request)) in Router.php line 639
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 xdomain.php line 23
at xdomain->handle(object(Request), object(Closure))
at call_user_func_array(array(object(xdomain), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in VerifyCsrfToken.php line 50
at VerifyCsrfToken->handle(object(Request), object(Closure))
at call_user_func_array(array(object(VerifyCsrfToken), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in ShareErrorsFromSession.php line 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 42
at CheckForMaintenanceMode->handle(object(Request), object(Closure))
at call_user_func_array(array(object(CheckForMaintenanceMode), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Kernel.php line 122
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 87
at Kernel->handle(object(Request)) in index.php line 54
at require_once('/var/www/vhosts/prepay/httpdocs/public/index.php') in server.php line 21



via Chebli Mohamed

Laravel get_file_contents() replaces '&' with '&'

How can I avoid Laravel replacing '&' with '&' when calling get_file_contents? (I always get a "Bad Request" Response because of this) It is not a problem when not using Laravel.



via Chebli Mohamed

Issues importing XML with Laravel Package orchestral/parser

I have this XML that i'm trying to import:

    <products>
<product product_id="62" title="Product Title" description="<p>desc</p>" price="40" brand="" weight="100" in_stock="Y"/>
<product product_id="63" title="Product Title" description="<p>desc</p>" price="40" brand="" weight="100" in_stock="Y"/>
</products>

I'm using Laravel 5 and this package: http://ift.tt/1KBdWon

So i'm running this code:

    $xml = XmlParser::load('http://ift.tt/1OtIkWc');


    $product = $xml->parse([
    'product_id' => ['uses' => 'product::product_id'],
    'title' => ['uses' => 'product::title'],
    'description' => ['uses' => 'product::description'],
]);
    dd($product);

But it's just returning a single product in an array which isn't even the first or last one in the XML. So i'm a bit confused.

Anyone got any ideas?

Thanks.



via Chebli Mohamed

Laravel - insert multiple models from appended inputs

I'm new to Laravel and I'm trying to insert n models from n appended html inputs Does Laravel's `Eloquent have a better way than this ?

public function store(Request $request, Domain $domain, Server $server)
{
    $new_domain = $domain->create($request->all());
    $server->fill($request->only(['srv_hostname','srv_ip','srv_port']));
    $servers = array();
    $total = count($server['attributes']['srv_hostname']);
    for ($i=0;$i<$total;$i++){
        $p = new Server;
        $p->domain()->associate($new_domain);
        $p->srv_hostname = $server['attributes']['srv_hostname'][$i];
        $p->srv_ip = $server['attributes']['srv_ip'][$i];
        $p->srv_port = $server['attributes']['srv_port'][$i];
        $p->save();
    }
    return redirect()->route('domains.index');
}



via Chebli Mohamed

Laravel 5.1: SQL query 'where LIKE %word%word%word%' not working

Keep in mind I have minimal SQL experience, so I may be doing it all wrong.

I'm trying to set up search for a table but simply searching for the string a user enters is not ideal because though something may come up for "steve", if a user types "steve jobs story", nothing will match as it'll be looking for that whole string.

I tried to breack it down by exploding the string into an array and then imploding that and separating it with %'s, so a search like "steve jobs story" would be "steve%jobs%story", and with my query it would be "%steve%jobs%story%". When I try searching this, I get no error but the query finds nothing, whereas when I just type one word it works, so I'm guessing what I'm trying to do isn't allowed.

Can someone point me in the right direction? Here is my controller/model:

// Controller

$query = $request->get('q');

$explodedQuery = explode(" ", $query);
$newQuery = implode("%", $explodedQuery);

$articles = Article::isLikeTitle($newQuery)
                   ->isLikeBody($newQuery)
                   ->latest('published_at')
                   ->published()
                   ->paginate(10);

// Model

public function scopeIsLikeTitle($query, $q)
{
    return $query->where('title', 'LIKE', "%$q%");
}

public function scopeIsLikeBody($query, $q)
{
    return $query->where('body', 'LIKE', "%$q%");
}



via Chebli Mohamed

Laravel 5 - Helper on Blade not working

I have this error when I used {{ Helper::test(); }} on a blade

enter image description here

and on my config/app.php, I already have enter image description here

and this is inside of my Helper.php

<?php namespace App;

class Helper {
    public static function test() {
        return "wa";
    }
}

and I already done the composer.json then run the composer dump-autoload

...
"autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/"
        },
        "files": [
            "app/Helper.php"
        ]
    },
...

I don't know what I missed, is there any suggestion to be able to use the helper on a blade on a laravel 5?



via Chebli Mohamed

Laravel 5.1 firstOrNew

I want to be able to insert a new record into the database if it doesn't already exist. If it does exist I want to update the existing record with the new info.

Basically, the field that I want to check to see if it exists is called 'token'.

So, I have tried something like this:

$this->timesheet->firstOrNew(['token' => '12345'])->save();

This successfully creates the new row.

How do I pass in the other fields that I want to insert/update? For example first_name, last_name?

Can I do something like:

$this->timesheet->firstOrNew(['token' => '12345'])->update(['first_name' => 'Bob', 'last_name' => 'Smith'])->save();



via Chebli Mohamed