Wednesday, January 31, 2018

Laravel relationships changing table columns makes undefined property - development

Laravel relationships changing table columns makes undefined property

So I changed the name of a column in my Laravel app and the party started..

The change was from name_id to seller_id

Before in view:

$transaction->user->first_name

Before in controller Transaction:

class Transaction extends Model
{
    public function user(){
        return $this->belongsTo('AppUser');
    }
 }

After in view:

$transaction->seller->first_name

After in controller Transaction:

class Transaction extends Model
{
    protected $primaryKey = 'seller_id';

    public function user(){
        return $this->belongsTo('AppUser');
    }
}

After returns:

Trying to get property of non-object

For reference the table users has the standard name “user_id”

What I’m doing wrong?



from Laravel Questions and Answers https://laravelquestions.com/php/laravel-relationships-changing-table-columns-makes-undefined-property/
via Lzo Media

Upload photo PHP/Ajax - development

Upload photo PHP/Ajax

I’m trying to upload a photo with Ajax and PHP, but return an error, and I don’t know why:

message: “move_uploaded_file(/site/uploads/users/user.png): failed to
open stream: No such file or directory”

RETURN (FILE):

C:xampptmpphp2BAB.tmp

JQUERY:

$("#user-upload-photo").submit(function (){

        $("#user-upload-photo").ajaxSubmit({
            url: '/ajax/settings/upload',
            type: 'post',
            beforeSubmit: function(){
                $("#photo-loading").show();
                $("#photo-figure").hide();
            },
            success: function () {
                $("#photo-loading").hide();
                $("#photo-figure").show();
            }
        });

    return false;
});

This is the code that return the error:

Controller:

public function upload(){
    if(!empty($_FILES)):
        if(is_uploaded_file($_FILES['user-photo-input']['tmp_name'])):
            $srcPath = $_FILES['user-photo-input']['tmp_name'];
            $trgPath = '/site/uploads/users/' . $_FILES['user-photo-input']['name'];

            if(move_uploaded_file($srcPath, $trgPath)):
                return response()->json(['succcess' => '1', 'photo' => $trgPath]);
            endif;

        endif;
    endif;
}



from Laravel Questions and Answers https://laravelquestions.com/php/upload-photo-php-ajax/
via Lzo Media

UK Based Remote PHP Developer - development

UK Based Remote PHP Developer



from Laravel Questions and Answers https://laravelquestions.com/top-laravel-jobs/uk-based-remote-php-developer/
via Lzo Media

call route in laravel blade if exists only - development

call route in laravel blade if exists only

I have an ajax function which will use an URL.

ajaxMyFunction('', function (result) { //do stuff });

I want to call the route only if it exists in my dynamic route list because Laravel throws exception if myroute.route1 doesn’t exist yet.

Is there a way to check route before render it inside blade, like when we check views ?

@if(View::exists('myroute.route1'))

I tried, Route::has('myroute.route1') but it doesn’t work as well.

Thanx for your help guys 😉



from Laravel Questions and Answers https://laravelquestions.com/laravel/call-route-in-laravel-blade-if-exists-only/
via Lzo Media

Why app/Http/Middleware (singular) vs app/Http/Controllers (plural)? - development

Why app/Http/Middleware (singular) vs app/Http/Controllers (plural)?

And why app/Jobs and app/Mail?

submitted by /u/rap2h
[link] [comments]



from Laravel Questions and Answers https://laravelquestions.com/rlaravel/why-app-http-middleware-singular-vs-app-http-controllers-plural/
via Lzo Media

laravel migration error after define defaultStringLength - development

laravel migration error after define defaultStringLength

i get this error after define ‘defaultStringLength’

[SymfonyComponentDebugExceptionFatalErrorException]
Call to undefined method
IlluminateDatabaseSchemaMySqlBuilder::defaultSt ringLength()



from Laravel Questions and Answers https://laravelquestions.com/php/laravel-migration-error-after-define-defaultstringlength/
via Lzo Media

How to connect laravel app to mysql database hosted on a digital ocean server? [on hold] - development

How to connect laravel app to mysql database hosted on a digital ocean server? [on hold]

I want to connect mysql database on my digital ocean server to my laravel app.
I can connect to mysql server remotely through apps like sequel pro. But i have to use SSH connection method.
How do i set up the db connection configurations on my .env file with such setup ?



from Laravel Questions and Answers https://laravelquestions.com/laravel/how-to-connect-laravel-app-to-mysql-database-hosted-on-a-digital-ocean-server-on-hold/
via Lzo Media

Undefined variable: editor (View: /home/marco/prova/resources/views/home.blade.php) - development

Undefined variable: editor (View: /home/marco/prova/resources/views/home.blade.php)

I have a problem, blade not find the variable: editor.
This is the function of my Controller.

public function HomeText()
{
    $data = [];
    $data['editor'] = Editore::get();

    return view('home')->with($data);
}

And these are the instructions in the file blade.php:

<select class="form-control select_editore">
@foreach ($editor as $editore)
<option></option>
@endforeach  </select>

What is the error?
I hope that you help me!
I’m newbie with Laravel,
I want to understand where I’m wrong.



from Laravel Questions and Answers https://laravelquestions.com/php/undefined-variable-editor-view-home-marco-prova-resources-views-home-blade-php/
via Lzo Media

Form AJAX post response cycle in Laravel 4.1.* - development

Form AJAX post response cycle in Laravel 4.1.*

I have a rather old site that I have inherited as part of a new position – it’s been built to Laravel 4.1.* version specs.

My issue is Response::json returning undefined variables in the response, using standard AJAX post method with all CSRF stuff and ajaxSetup() defined correctly.

application.blade.php

 $.ajax({
   type: 'POST', //This will always be a post method for the supplier chain check form.
   url: 'supply-us/application', //URL endpoint for the post form method: we'll set this to the controller function we're targeting.
   data: { 'companyName': values['companyName'] }, //This will carry the form data that is needed to be passed to the server.
   success: function (response) {
       console.log(response['companyName']); << THIS LINE RETURNS "undefined"

       console.log(typeof response) << THIS LINE RETURNS string
   },
   error: function (response) {
       console.log(response);
   },
 }); 

values[‘companyName’] returns what I input into the form. The above “response” simple chucks back html – so I think my routes might be incorrectly defined or incorrectly defined in the AJAX url param, perhaps? Here are the two applicable routes:

routes.php

Route::controller('supply-us/application', 'ApplicationController');
Route::post('supply-us/application', 'ApplicationController@processSupplierApplication');

ApplicationController.php:

<?php

use IlluminateHttpRequest;

class ApplicationController extends FrontController {
  public function getSupplierApplication() {
         return self::getPage('supply-us/application');
    }

  public function processSupplierApplication(Request $request) {
    if (Input::has('companyName')) {

       $this->companyName = Input::get('companyName');

       $data = [
          'success': true,
          'companyName': $this->companyName
       ];

       return response()->json($data);

    }

  }

}

Any pro-tips would be greatly appreciated!



from Laravel Questions and Answers https://laravelquestions.com/php/form-ajax-post-response-cycle-in-laravel-4-1/
via Lzo Media

Hierarchy of Including css files in laravel to avoid css overriding - development

Hierarchy of Including css files in laravel to avoid css overriding

I’m not too much familiar with the front end development since I’ve worked as back-end developer. Now, I’ve a problem with css overriding on my page.

I’ve following a structure including css files in the master layout.

@section('assets')
    <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,700,700i|Raleway:300,400,500,700,800" rel="stylesheet">
    <link rel="stylesheet" href="">
    <link href="" rel="stylesheet">
    <link href="" rel="stylesheet">
    <link href="" rel="stylesheet">
    <link href="" rel="stylesheet">
    <link href="" rel="stylesheet">
@show()

Whenever the home page is loaded then I have a lot of errors displayed in the console.

Unknown property ‘-moz-osx-font-smoothing’. Declaration dropped. font-awesome.min.css:4:662

Error in parsing value for ‘-webkit-text-size-adjust’. Declaration dropped. bootstrap.min.css:7:329

Unknown pseudo-class or pseudo-element ‘-webkit-search-cancel-button’. Ruleset ignored due to bad selector. bootstrap.min.css:7:1619

Unknown property ‘orphans’. Declaration dropped.
bootstrap.min.css:7:2379

Unknown property ‘widows’. Declaration dropped.
bootstrap.min.css:7:2388

Error in parsing value for ‘outline’. Declaration dropped.
bootstrap.min.css:7:3249

Error in parsing value for ‘margin-top’. Declaration dropped.
bootstrap.min.css:7:21595

Error in parsing value for ‘outline’. Declaration dropped.
bootstrap.min.css:7:21882
….

As per my knowledge, this is because of conflict of css rules added in files and hence proper ordering of the including css files that master blade needs.

Can anyone provide how to reorder the including css files in above master layout?

Thanks in advance.



from Laravel Questions and Answers https://laravelquestions.com/php/hierarchy-of-including-css-files-in-laravel-to-avoid-css-overriding/
via Lzo Media

How tags are used with Laravel Horizon - development

How tags are used with Laravel Horizon

My tracking tags in job queue does not show the tags I expect. Job does not process after change to class.

My job example class is :

class EmailUser implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * The user instance.
     *
     * @var AppUser
     */
    public $user;

    /**
     * Create a new job instance.
     *
     * @param  AppUser  $user
     * @return void
     */
    public function __construct(User  $user)
    {
        $this->user = $user;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        Mail::to('fesher@example.com')->send(new ApplicationReceivedEmail());
    }

   /**
     * Get the tags that should be assigned to the job.
     *
     * @return array
     */
    public function tags()
    {
        return ['email', 'user:'.$this->user];
    }
}

Now before I manually tag job class emails are sent normally and all works. Adding tags method kills process, emails are no longer sent normally.

I go from example on website here https://laravel.com/docs/5.5/horizon#tags

Someone can help? Thanks



from Laravel Questions and Answers https://laravelquestions.com/php/how-tags-are-used-with-laravel-horizon/
via Lzo Media

Laravel with relation has record then fetch - development

Laravel with relation has record then fetch

I am working in laravel project and now I want to search only those users whose are friend of viewing user other wise fetch those users whose are allowed to chat with every one. Below is my working code that I code

public static function hasSearchTagable($searchText = null, $user_id) {
        if (empty(trim($searchText))) {
            return self::where(function($sql) use($user_id) {
                        $sql->where('archive', '=', false);
                        $sql->whereHas('follower_friend', function($sql) use($user_id) {
                            $sql->where('following_id', '=', $user_id);
                        });
                    });
        } else {
            $searchText = trim(preg_replace('/[^A-Za-z0-9._ -]/', '', strtolower($searchText)));
            return self::where(function($sql) use($searchText) {
                        $sql->where('archive', '=', false);
                        $sql->where('username', 'LIKE', "%$searchText%")->orWhere('full_name', 'LIKE', "%$searchText%");
                    })->with(['follower_friend' => function($sql) use($user_id) {
                            $sql->where('following_id', '=', $user_id);
                        }])->with(['following_friend' => function($sql) use($user_id) {
                            $sql->where('follower_id', '=', $user_id);
                        }]);
        }
    }


public static function get_tagable_users($login_id, $searchText = null, $not_in = array(), $take = 40, $skip = 0, $is_messageable = false) {
        $orderBy = "  username DESC ";
        if (!empty(trim($searchText))) {
            $searchText = preg_replace('/[^A-Za-z0-9-_.]/', '', strtolower(trim($searchText)));
            $orderBy = "  CASE WHEN username = '$searchText' THEN 0  
              WHEN username LIKE '$searchText%' THEN 1  
              WHEN username LIKE '%$searchText%' THEN 2  
              WHEN username LIKE '%$searchText' THEN 3  
              WHEN full_name LIKE '$searchText%' THEN 4  
              WHEN full_name LIKE '%$searchText%' THEN 5  
              WHEN full_name LIKE '%$searchText' THEN 6  
              ELSE 7
              END, username ASC ";
        }

        $users = User::hasSearchTagable($searchText, $login_id)->whereNotIn('id', $not_in)
                ->take($take)->skip($skip)
                ->orderByRaw($orderBy)
                ->get(array('id', 'username', 'full_name', 'message_privacy', 'picture'));
        return !empty($users) ? $users->toArray() : array();
    }

if I search people then it search public and private both users. But if private user is in following or followers list then it should come into search but if not then if this user allowed user to chat tjem it should come.



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-with-relation-has-record-then-fetch/
via Lzo Media

Laravel Forge/Envoyer using old releases since upgrading to 5.5 - development

Laravel Forge/Envoyer using old releases since upgrading to 5.5

I am experiencing very strange behavior since upgrading to Laravel 5.5, where the site will continue to show an old release after successfully deploying with Envoyer.

The current folder is correctly set to the newest release, however the site still shows the old release.

If the old release folder is manually deleted, or gets deleted via deploying enough times, the entire site will break, and this shows up:

Warning: include(/home/forge/sitefoo.com/envoyer/releases/20180130124512/vendor/composer/../vlucas/phpdotenv/src/Exception/InvalidPathException.php): failed to open stream: No such file or directory in /home/forge/sitefoo.com/envoyer/releases/20180130124512/vendor/composer/ClassLoader.php on line 444

Warning: include(): Failed opening '/home/forge/sitefoo.com/envoyer/releases/20180130124512/vendor/composer/../vlucas/phpdotenv/src/Exception/InvalidPathException.php' for inclusion (include_path='.:/usr/share/php') in /home/forge/sitefoo.com/envoyer/releases/20180130124512/vendor/composer/ClassLoader.php on line 444

Warning: include(/home/forge/sitefoo.com/envoyer/releases/20180130124512/vendor/composer/../symfony/debug/Exception/FatalThrowableError.php): failed to open stream: No such file or directory in /home/forge/sitefoo.com/envoyer/releases/20180130124512/vendor/composer/ClassLoader.php on line 444

Warning: include(): Failed opening '/home/forge/sitefoo.com/envoyer/releases/20180130124512/vendor/composer/../symfony/debug/Exception/FatalThrowableError.php' for inclusion (include_path='.:/usr/share/php') in /home/forge/sitefoo.com/envoyer/releases/20180130124512/vendor/composer/ClassLoader.php on line 444

Fatal error: Uncaught Error: Class 'SymfonyComponentDebugExceptionFatalThrowableError' not found in /home/forge/sitefoo.com/envoyer/releases/20180130124512/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php:122 Stack trace: #0 /home/forge/sitefoo.com/envoyer/releases/20180130124512/public/index.php(53): IlluminateFoundationHttpKernel->handle(Object(IlluminateHttpRequest)) #1 {main} thrown in /home/forge/sitefoo.com/envoyer/releases/20180130124512/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php on line 122

Once you restart the server after deleting the old folder, everything will go back to normal and the correct release will be used.

Does anyone have any ideas on what’s going wrong or how to solve this problem?

Thanks



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-forge-envoyer-using-old-releases-since-upgrading-to-5-5/
via Lzo Media

phpunit method viaRemember doesnt exist – laravel 5.4 - development

phpunit method viaRemember doesnt exist – laravel 5.4

i am using laravel and php unit test, every time i ran the unit test it always show errors like this, i went deep through the framework and found nothing.

can somebody help? its so frustrating, thanks

here’s the error looks like

PHPUnit 5.7.26 by Sebastian Bergmann and contributors.

1)
TestsFeatureCreateCitiesTest::an_authenticated_user_can_create_a_city
BadMethodCallException: Method viaRemember does not exist.



from Laravel Questions and Answers https://laravelquestions.com/php/phpunit-method-viaremember-doesnt-exist-laravel-5-4/
via Lzo Media

laravel call to undefined method Auth guard - development

laravel call to undefined method Auth guard

i want to prevent the login after register in Laravel 5.5, I already did this by commenting a line:

public function register(Request $request)
    {
        $this->validator($request->all())->validate();

        event(new Registered($user = $this->create($request->all())));

    //    $this->guard()->login($user);

        return $this->registered($request, $user)
                        ?: redirect($this->redirectPath());
    }

i override it in RegisterController.php

i got this error:

Call to undefined method IlluminateAuthAuthenticationException::guard()
    $guard = array_get($exception->guard(),0);
    switch ($guard) {
        case 'admin':
            return redirect()->guest(route('admin.login'));
            break;

        default:
            return redirect()->guest(route('login'));
            break;
    }

Here is the content of my config/auth:

<?php

return [



    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],



    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],
        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],
    ],



    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => AppUser::class,
        ],
        'admins' => [
            'driver' => 'eloquent',
            'model' => AppAdmin::class,
        ],


    ],



    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
        ],
        'admins' => [
            'provider' => 'admins',
            'table' => 'password_resets',
            'expire' => 60,
        ],
    ],

];

i have enabled multi-auth system which is i have an admin login and a user login, what i wan’t is to disable the login after register in my user page.



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-call-to-undefined-method-auth-guard/
via Lzo Media

How to catch all exceptions in Laravel - development

How to catch all exceptions in Laravel

I was wondering if there is a way to catch all the exceptions that are thrown in a laravel app and store them in database ?

I have been looking at some packages but coudn’t find anything that tells where and how to catch the exceptions.



from Laravel Questions and Answers https://laravelquestions.com/laravel/how-to-catch-all-exceptions-in-laravel/
via Lzo Media

Laravel : Data not inserted on the table - development

Laravel : Data not inserted on the table

Facing a problem on submit form data.

When I fill up all form data then it is inserted into the database. But when I fill only mandatory field data and leave other data as blank it is not working and it redirect to the same form.

On removing validation also not working.

My controller function code:

public function save(Request $request) {
    try {
        $validator = Validator::make($request->all(), Activity::rules());
        $activity = Activity::saveOrUpdate($request);
        if($activity !== false) {
            return redirect()->route('lists-activity')->with('success', trans('activity data added successfully.!!'));
        } else {
            return back()->with('error', "Unable to save activity data.!!")->withInput();
        }
    } catch (Exception $ex) {
       return back()->with('error', "Unable to save activity data.!!")->withInput()->withErrors($validator);
    }
}

My model code :

  namespace App;

  use IlluminateHttpRequest;
  use IlluminateDatabaseEloquentModel;
  use IlluminateSupportFacadesDB;
  use IlluminateSupportFacadesInput;

 class Activity extends Model
 {
/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'category_id',
    'title',
    'description',
    'country_id',
    'city_id',
    'latitude',
    'longitude',
    'addressOne',
    'addressTwo',
    'hours_recomended',
    'hours_fixed',
    'time_fixed',
    'start_time',
    'end_time',
    'file_type',
    'flag_image'
];


/**
 * Indicates if the model should be timestamped.
 *
 * @var bool
 */
public $timestamps = false;

public static function rules() {
    return [
        'category_id' => 'required',
        'title' => 'required|string|max:255',
        'country_id' => 'required',
        'city_id' => 'required',
        'hours_fixed' => 'required',
        'start_time' => 'required',
        'end_time' => 'required'
    ];
}
  public static function saveOrUpdate(Request $request) {
    try {
        $id = $request->get('id', false);
        $activity = false;
        DB::transaction(function () use ($request, &$activity, $id) {

            $activity = $id ? Activity::findOrFail($id) : new Activity();
            $activity->fill($request->all());
            try {

                $activity->save();
            } catch (Exception $ex) {
                throw $ex;
            }
        });
        return $activity;
    } catch (Exception $ex) {
        throw $ex;
    }

} }

Form view :
enter image description here
Don’t know what I am doing wrong?



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-data-not-inserted-on-the-table/
via Lzo Media

Header of grid stays after removal of all data of grid laravel - development

Header of grid stays after removal of all data of grid laravel

I have a design of grid in controller that displays me all data of selected check boxes.
This grid gets appended to a span through ajax.
While performing a delete request, one by one my data in grid gets deleted,
but the grid header stays as it is.

This is my design of grid in controller:

 $res_div = '';
$res_div.='<table width="100%" border="0"  class="table table-striped table-bordered table-hover">';
        $res_div.='<tr>
                   <th width="100%">SublawId</th>
                   <th width="100%">Sublawname</th>
                   <th width="100%">View</th>
                   <th width="100%">Update</th>
                   </tr>';
        foreach ($law as $sublaw)
        {
            $law_details = DB::table('tbl_law_sub_master')->where('id', $sublaw->id)->select('*')->first();
            $res_div.='<tr>
                       <td>
                       <strong>'.$law_details->lms_id.'</strong>
                       </td>
                       <td>
                       <strong>('.$law_details->sub_law_name.')</strong>
                       </td>
                       <td align="center">
                       <input type="checkbox" id="cb1" onclick="ts(this)" class="cb1" name="viewsub_'.$sublaw->id.'">
                       </td>
                       <td align="center">
                       <input type="checkbox" id="cb1" onclick="ts(this)" class="cb1" name="updatesub_'.$sublaw->id.'">
                        </td>
                        </tr>';
        }
        $res_div.='</table>';
        $data=array(
            'res_div'=>$res_div,
            'law'=>$law
        );    
        return json_encode($data);

my ajax request on blade:

$.ajax({
      url: "?sub_law_id="+sublaw_ids.join(),
      type: 'POST',
      dataType: "json",
      data: formData,
      async: false,
      cache: false,
      contentType: false,
      processData: false,
      success: function (returndata) {
      var res_sublaw_content=returndata.res_div;
      var data = document.getElementById("append_sublaw_grid").innerHTML = "";                                            $('#append_sublaw_grid').append(res_sublaw_content);
      return false;
       }
});

On deletion all data gets deleted one by one from grid, but its header stays..

A screenshot:

image



from Laravel Questions and Answers https://laravelquestions.com/laravel/header-of-grid-stays-after-removal-of-all-data-of-grid-laravel/
via Lzo Media

laravel Goutte filter some of text is return right result while some is return nothing - development

laravel Goutte filter some of <td> text is return right result while some is return nothing

Hi i am using laravel Goutte package to crawl some specific data for data analysis in my project while i am applying the filter some of td is return the right result while some is not return result anyone have the idea please help my controller code is

namespace AppHttpControllers;

use IlluminateHttpRequest;
use Goutte;
use GoutteClient;
 use AppHttpRequests;
class MapController1 extends Controller
{
    //
  public function index()
   {

   $crawler = Goutte::request('GET', 'http://www.upsldc.org/real-time-data');
    $crawler->filter('body')->each(function ($node) {
      echo "<pre>";
      //var_dump($node->text());
      echo $node->filter('td')->eq(0)->text();
       echo $node->filter('td.up_schedule')->text();
       echo $node->filter('td')->eq(2)->text();

    });


   }
}

it is return Schedule (MW)Drawl (MW) but this echo $node->filter(‘td.up_schedule’)->text(); row is return nothing. Thanks in advance



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-goutte-filter-some-of-td-text-is-return-right-result-while-some-is-return-nothing/
via Lzo Media

Benefit of using the newer Laravel Mix over Elixir - development

Benefit of using the newer Laravel Mix over Elixir

Since Laravel 5.4, the default method to compile assets is using Laravel Mix, instead of elixir. I’ve been messing with it for a few hours, but I cannot see any benefit to this approach over elixir. The documentation didn’t really mention any reason why “Mix” was supposed to be better.

I know that “Mix” uses WebPack by default to compile the assets…. but I can’t see how this is a plus. The Mix also allows you to compile without WebPack, and this always produces files that are smaller in size and work the same.

So if the new method using WebPack always produces larger JS files that do the same thing as the smaller JS files I was making with Elixir, what is the benefit of using Laravel Mix with WebPack?

Sorry, Just trying to understand here :/

So for example, this:

mix.js(source, target);

produces a slightly larger JS file than this:

mix.scripts(source, target);

So what makes the first option better? (since this is the newer, suggested approach)



from Laravel Questions and Answers https://laravelquestions.com/laravel/benefit-of-using-the-newer-laravel-mix-over-elixir/
via Lzo Media

Tuesday, January 30, 2018

Displaying an image over another image - development

Displaying an image over another image

I have a carousel showing images. Some of them are thumbs of youtube video in that case i want an image of a play button to be displayed over the thumb image to show that it is a video not a simple image.

<div class="carousel-inner">
            @foreach($realisation->images as $key => $img)
                @if($img->type == 'image')
                <div class="item "> 
                    @if(File::exists($img->image))
                        <img src="" class="image" alt="realisation"/> 
                    @endif
                </div>
                @else
                <div class="item "> 
                    <a href=""  data-lity>
                        <img src="" class="image" alt="realisation">
                        <img src=""  alt="">
                    </a>  
                </div>
                @endif
            @endforeach
        </div>



from Laravel Questions and Answers https://laravelquestions.com/laravel/displaying-an-image-over-another-image/
via Lzo Media

SQLSTATE[HY000]: General error: 1364 Field ‘user_id’ doesn’t have a default value (SQL - development

SQLSTATE[HY000]: General error: 1364 Field ‘user_id’ doesn’t have a default value (SQL

I am trying to save my data against my userid but i am getting this error.
My code is:

        AppKeys::create([
         $user = IlluminateSupportFacadesAuth::user(),
        'user_id' => $user,
        'accessTokenKey' => $accessTokenKey,
        'accessTokenSecret' => $accessTokenSecret
    ]);
    return 'You have successfully granted';

I am getting error user_id does not have default value and when i passed Auth::user()->id it says trying to get properties of non object id.

Any help would be appreciated!



from Laravel Questions and Answers https://laravelquestions.com/php/sqlstatehy000-general-error-1364-field-user_id-doesnt-have-a-default-value-sql/
via Lzo Media

Laravel jordanmiguel/laravel-popular error - development

Laravel jordanmiguel/laravel-popular error

I’m using Laravel/popular and when i add 3 classes and migrate it gives me error. Here that 3 classes are listed:

JordanMiguelLaravelPopularLaravelPopularServiceProvider::class,
IlluminateFoundationProvidersArtisanServiceProvider::class,
IlluminateAuthAuthServiceProvider:class,

Laravel popular

In Connection.php line 664:

SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key
was too long; max key length is 1000 bytes (SQL: alter table visits
add unique visits_ip_visitable_id_visitable_type_date_unique(ip,
visitable_id, visitable_type, date))

In Connection.php line 458:

SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key
was too long; max key length is 1000 bytes



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-jordanmiguel-laravel-popular-error/
via Lzo Media

Laravel Spatie/Laravel-activitylog with Sentinel - development

Laravel Spatie/Laravel-activitylog with Sentinel

I’m using Sentinel for authorization on my Laravel project. Now i’m trying to add Laravel-activitylog from Spatie. Activity log uses default auth driver for logging user activity. How can i change driver to use the one from Sentinel. I’m new at Laravel and have trouble implementing this. Any help would be greatly appreciated. Kind regards.



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-spatie-laravel-activitylog-with-sentinel/
via Lzo Media

Sudomain automatically redirect to https - development

Sudomain automatically redirect to https

I’m having HTTPS with my main domain ie https://example.com.
And I want to use subdomain without HTTPS ie, http://hello.example.com but the problem is it automatically redirects to HTTPS. How do I avoid that?

This is my current .htaccess structure:

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

    RewriteEngine On

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] 

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

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>



from Laravel Questions and Answers https://laravelquestions.com/php/sudomain-automatically-redirect-to-https/
via Lzo Media

Laravel manually update timestamps returns null - development

Laravel manually update timestamps returns null

I have an offer with some children.

I want to update expire_time field of each children when their parent expire_time field changed.

but it returns null.

expire_time type is timestamps.

and here is my code in model:

if ($offer->childrenOffers->count()) {
        $offer->childrenOffers->each(function (self $childOffer) use($offer) {

            ddd($offer->expire_time); //returns "2018-02-30 23:59:59"
            ddd($childOffer->expire_time); //returns "2018-02-01 23:59:59"

            $childOffer->expire_time = $offer->expire_time;

            dd($childOffer->expire_time); //returns null

            $childOffer->save();
        });
    }

How can i do this ?!



from Laravel Questions and Answers https://laravelquestions.com/php/laravel-manually-update-timestamps-returns-null/
via Lzo Media

Laravel relationship with single column - development

Laravel relationship with single column

I have a table called “fields”:

Schema::create('fields', function (Blueprint $table) {
    $table->increments('id');
    $table->string("label");
    $table->string("name")->unique();
    $table->text("options")->nullable();
    $table->timestamps();
});

I want to have another table which simply stores the ids of some of the fields. I will call this default_fields.

I basically want a relationship or logic that allows me to grab these default_fields like I would with any other relation:

Schema::create('default_fields', function (Blueprint $table) {
    $table->increments('id');
    $table->integer("field_id");
});

How can I create a relationship that grabs all the fields whose id’s are present in this table? I also want to be able to sync().

Would I just make a model for DefaultField and then do something like Field::whereIn('id', DefaultField::get()->pluck('id'))?

And then code my own sync() logic? Is there a super easy way to do this that I’m missing? I’d also like to be able to sort this like I would any other relation.



from Laravel Questions and Answers https://laravelquestions.com/php/laravel-relationship-with-single-column/
via Lzo Media

Laravel 5.6 release notes - development

Laravel 5.6 release notes

Laravel 5.6 release notes submitted by /u/rap2h
[link] [comments]


from Laravel Questions and Answers https://laravelquestions.com/rlaravel/laravel-5-6-release-notes/
via Lzo Media

Multiple queues on the same server with Laravel Forge - development

Multiple queues on the same server with Laravel Forge

I’ve three of the same Laravel Application running but on different environments using Laravel Forge.

Let’s say these are the three sites:

  • site.com (production)
  • staging.site.com (staging)
  • dev.site.com (develop)

On the production site I run Laravel Horizon to monitor the queues for the production site.

When I run a password reset on my dev.site.com the email is not sending to the user because of Exception which happens in queue.

IlluminateDatabaseEloquentModelNotFoundException: No query results
for model [AppModelsUser]. in
/home/forge/site.com/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:412

If you look closely in the error you’ll see that the errors occurred on the site.com production environment. So an email is put on queue in the develop environment, but is executed in the production environment.

This is my queue.php config:

<?php

return [

    'default' => env('QUEUE_DRIVER', 'high'),

    'connections' => [

        'sync' => [
            'driver' => 'sync',
        ],

        'high' => [
            'driver' => 'redis',
            'connection' => 'default',
            'queue' => 'default',
            'retry_after' => 90,
        ],

        'medium' => [
            'driver' => 'redis',
            'connection' => 'default',
            'queue' => 'default',
            'retry_after' => 90,
        ],

        'low' => [
            'driver' => 'redis',
            'connection' => 'default',
            'queue' => 'default',
            'retry_after' => 90,
        ],

    ],

    'failed' => [
        'database' => env('DB_CONNECTION', 'mysql'),
        'table' => 'failed_jobs',
    ],

];

These are the queue settings on all three environments on Forge:

Laravel Forge Queue config

Is this normal behaviour? Or is there something which I’m doing wrong?



from Laravel Questions and Answers https://laravelquestions.com/php/multiple-queues-on-the-same-server-with-laravel-forge/
via Lzo Media

How to retrieve user name from user table by using data (user_id) from another table having relationship - development

How to retrieve user name from user table by using data (user_id) from another table having relationship

I have two models

User.php

public function opportunities()
{
    return $this->hasMany('AppOpportunity');
}

Opportunity.php

public function user()
{
    return $this->belongsTo('AppUser');
}    

I have user_id column in opportunities table and inserted user id (from user table using Auth) every time user posts record.

Now i need a view to return “this post is posted this user”.

First I find the post id by

$posts =  Opportunity::find($id);
$posted_by = User::find($posts->user_id);
return view('opportunity.detail')->with('post', $posts, 'posted_by', $posted_by);

I have rendered user name by

But I got undefined constant in the view file $posted_by while $post is fine. Am I doing it in right way or not? I am passing two array variable to the post and its not working. Any help will be appreciated.



from Laravel Questions and Answers https://laravelquestions.com/laravel/how-to-retrieve-user-name-from-user-table-by-using-data-user_id-from-another-table-having-relationship/
via Lzo Media