mardi 31 juillet 2018

Where is the syntax missing in this code?

I had this code for db seed in laravel 5.

But when I run, it gives syntax error expecting end file error.. This is using spatie permission package..

this is the code:

<?php
use Illuminate\Database\Seeder;
use App\Permission;
use App\Role;
use App\User;
use App\Post;

 class DatabaseSeeder extends Seeder
{
/**
 * Run the database seeds.
 *
 * @return void
 */
public function run()
{
    // Ask for confirmation to refresh migration
    if ($this->command->confirm('Do you wish to refresh migration before seeding, Make sure it will clear all old data ?')) {
        $this->command->call('migrate:refresh');
        $this->command->warn("Data deleted, starting from fresh database.");
    }
    // Seed the default permissions
    $permissions = Permission::defaultPermissions();
    foreach ($permissions as $permission) {
        Permission::firstOrCreate(['name' => $permission]);
    }
    $this->command->info('Default Permissions added.');
    // Ask to confirm to assign admin or user role
    if ($this->command->confirm('Create Roles for user, default is admin and user? [y|N]', true)) {
        // Ask for roles from input
        $roles = $this->command->ask('Enter roles in comma separate format.', 'Admin,User');
        // Explode roles
        $rolesArray = explode(',', $roles);
        // add roles
        foreach($rolesArray as $role) {
            $role = Role::firstOrCreate(['name' => trim($role)]);
            if( $role->name == 'Admin' ) {
                // assign all permissions to admin role
                $role->permissions()->sync(Permission::all());
                $this->command->info('Admin will have full rights');
            } else {
                // for others, give access to view only
                $role->permissions()->sync(Permission::where('name', 'LIKE', 'view_%')->get());
            }
            // create one user for each role
            $this->createUser($role);
        }
        $this->command->info('Roles ' . $roles . ' added successfully');
    } else {
        Role::firstOrCreate(['name' => 'User']);
        $this->command->info('By default, User role added.');
    }

}
/**
 * Create a user with given role
 *
 * @param $role
 */
private function createUser($role)
{
    $user = factory(User::class)->create();
    $user->assignRole($role->name);
    if( $role->name == 'Admin' ) {
        $this->command->info('Admin login details:');
        $this->command->warn('Username : '.$user->email);
        $this->command->warn('Password : "secret"');
    }
}

}

I already tried to check the code but failed to detect the syntax missing.

Can anyone help me to detect the problem in the code?

Thank you.



via Chebli Mohamed

Overriding where conditions in Laravel Query builder

I am working on E-Commerce application, in which I am fetching the product which has the status 1. But there are situations where I need to fetch the product which has status 2 or 3.

I have overridden the newQuery method and added a condition for status 1 in that method. Now I want to add another condition for status 2, but when I add this condition, the where clause will be duplicated in SQL query for that column(the default behavior of query builder).

Below is my code,

public function newQuery($excludeDeleted = true) {
    return parent::newQuery($excludeDeleted)
     ->where('status', 1);                
}

When I need to fetch the product with status 2 as below

return $query->where('status', 2);

then the query formed will be as below

select * from `products` where `status` = 1 and `status` = 2

But I need an output like below query

select * from `products` where `status` = 2

Please suggest the way of doing it.



via Chebli Mohamed

sscan redis laravel 5.4 cloud 9

I am trying to use sscan redis for laravel in cloud 9. I have used this function on localhost and try to dd the code , it works perfectly with this one :

dd($this->redis->sscan('events:'.$eid.':tickets' , null , '*:'.$name))

output on postman :

array:4 [
  0 => "Ct1yaZ2Q0Z:VIP Ticket"
  1 => "5vXsIqYvpF:VIP Ticket"
  2 => "jwCEU0lDXX:VIP Ticket"
  3 => "1mloEc8bFW:VIP Ticket"
]

However , with the same thing on cloud 9 , no changes and i tried to dd that function , it gives me output like this when there is no data :

array:2 [
  0 => "0"
  1 => []
]

and error page says ERR syntax error when there is data that match in the sets.

But when there is data in the sets and I add the 'match' keyword on cloud 9 like this :

dd($this->redis->sscan('events:'.$eid.':tickets' , null ,'match','*:'.$name));

it works but the output format is different and become like this :

array:2 [
  0 => "0"
  1 => array:4 [
    0 => "5xI4hCpuSU:VIP Ticket"
    1 => "E9ottqlLkk:VIP Ticket"
    2 => "VzJB5RfegK:VIP Ticket"
    3 => "8TwVvqTmEK:VIP Ticket"
  ]
]

I wonder why it gives output and error differently on cloud 9 while it works perfectly in localhost, does this mean redis in cloud 9 has different syntax ?



via Chebli Mohamed

Laravel middleware redirecting from dashboard to login page

I have written simple code for login but when I

if (Auth::guard('admin')->attempt($credentials)) {
            //dd(Auth::guard('admin')->check());
            return redirect()->intended(route('admin.dashboard'));
 }

(when I dd(Auth::guard('admin')->check()) in this I get true on login page but when I check that on dashboard I get false in Auth::guard('admin')->check()

public function __construct()
    {

      $this->middleware('auth:admin');

    }

    public function index(Request $request)
    {

        //dd(Auth::guard('admin')->check());
        return view('admin.dashboard');
    }

I don't know why the session is being destroyed after redirecting to dashboard controller.

Please let me know any other inputs you want from my side.



via Chebli Mohamed

difficulty on the integration of paypal on laravel

This is my first time to implement paypal on my project. I'm using srmklive/laravel-paypal and on the documentation i tested the following code

this is my controller

class CheckoutController extends Controller
{
    protected $provider;
    public function __construct(){
        $this->provider = new ExpressCheckout();
    }

    public function getExpressCheckout(Request $request){
        $data = [];
        $data['items'] = [
          [
            'name' => 'Product 1',
            'price' => 9.99,
            'qty' => 1
          ],
          [
            'name' => 'Product 2',
            'price' => 4.99,
            'qty' => 2
          ]
        ];

        $data['invoice_id'] = 2;
        $data['invoice_description'] = "test";
        $data['return_url'] = url('/');
        $data['cancel_url'] = url('/cart');

        $total = 0;
        foreach($data['items'] as $item) {
            $total += $item['price']*$item['qty'];
        }

        $data['total'] = $total;

        //give a discount of 10% of the order amount
        $data['shipping_discount'] = round((10 / 100) * $total, 2);
        $response = $this->provider->setExpressCheckout($data);
        return redirect($response['paypal_link']);
    }
 }

this is my route

Route::get('/paypal/ec-checkout', 'CheckoutController@getExpressCheckout')->name('checkout');

this is my link

 <a href="" class="btn btn-primary pull-right" style="margin-bottom:20px;">Checkout</a>

My problem is when i clicked the link it just load forever and no errors are shown. I'm using laravel 5.6



via Chebli Mohamed

Laravel passport allow only one user to log in?

I created an app with laravel & vuejs, for authentication i used laravel-passport. When i create new user and try log in browser returns this error.

POST http://127.0.0.1:8000/oauth/token 401 (Unauthorized)

but it only works for one user and only for that user, when log in using that doesn't return any error it works fine.

i create new user by following controller method

public function store(Request $request)
{
    $this->validate($request, [
        'name'=> 'required|max:120',
        'email'=> 'required|email|unique:users',
        'password'=> 'required|min:6'
    ]);
    return User::create([
    'name' => $request['name'],
    'email' => $request['email'],
    'password' => Hash::make($request['password']),
    ]);
}

and the log in method,

login(){
     var data = {
      username: this.user.email,
      password: this.user.password,
      client_id: 2,
      client_secret: 'wcw9GkgKMHXUnyZavawJWXgE3GhSubOADO6tKw99',
      grant_type: 'password'
    }
      this.$store.dispatch('login',data )
          .then( response =>{
            this.$router.push('dashboard');
          });
}

in store.js

login({ commit }, creds){
        commit(LOGIN);


        return new Promise((resolve) => {
            setTimeout(() =>{
                axios.post('/oauth/token', creds)
                .then((response) =>{
                    Vue.auth.setToken(response.data.access_token, response.data.expires_in + Date.now());
                    commit(LOGIN_SUCCESS);
                    alert(response.data.access_token)

                    axios.get('api/user', { headers: {"Authorization" : 'Bearer'+' '+response.data.access_token } })
                    .then( response =>{
                      console.log('success_(store.js)',response.data.id)
                      axios.post('api/role', { uid: response.data.id})
                      .then( response =>{
                         console.log('success_(store.js)',response.data["0"].name)
                         Vue.auth.setUserRole(response.data["0"].name);
                      })
                    })
                    .catch( response =>{
                       console.log('error_', response)
                    })
                    resolve();
                });
            }, 5000);               
        });
    }

any help ?



via Chebli Mohamed

Query hasMany relation with slug instead of id?

I'm trying to query a category and all of its channels based on a slug.

Works

\App\Category::find(1)->channels()->get();

Doesn't Work

\App\Category::where('slug','animals')->channels()->get()

BadMethodCallException with message 'Method Illuminate/Database/Query/Builder::channels does not exist.'

Relationship on Category Model

public function channels()
{
    return $this->hasMany(Channel::class,'category_id');
}



via Chebli Mohamed

TinyMce doesn't call audio_template_callback, but call instead video_template_callback

I am using TinyMce editor with laravel 5.6, and laravel-elfinder. I have to upload audio file, but editor doesn't recognize the audio file, so it render as video format by calling video_template_callback. So I change the editor_config like:

var editor_config = {
            selector: "textarea",
            plugins: [
            "image link lists textcolor imagetools table codesample textpattern media code"
            ], 
            video_template_callback: function(data){
                console.log('call video');
                return '<audio controls>' + '\n<source src="' + data.source1 + '"' + (data.source1mime ? ' type="' + data.source1mime + '"' : '') + ' />\n' + '</audio>';
            },
            audio_template_callback: function(data) {
                console.log('call audio');
                return '<audio controls>' + '\n<source src="' + data.source1 + '"' + (data.source1mime ? ' type="' + data.source1mime + '"' : '') + ' />\n' + '</audio>';
            },
            toolbar: "insertfile undo redo | styleselect | bold italic strikethrough | alignleft aligncenter alignright alignjustify | ltr rtl | bullist numlist outdent indent removeformat formatselect| link image media | emoticons charmap | code codesample | forecolor backcolor",
            browser_spellcheck: true,
            relative_urls: false,
            remove_script_host: false,
            media_poster: false,
            media_filter_html: false,
            file_browser_callback : function(field_name, url, type, win) {

                tinymce.activeEditor.windowManager.open({
                    file: '<?= route('elfinder.tinymce4') ?>',// use an absolute path!
                    title: 'File Manager',
                    width: 900,
                    height: 450,
                    resizable: 'yes'
                }, {
                    setUrl: function (url) {
                    win.document.getElementById(field_name).value = url;
                    }
                });
            },
            setup:function(ed) {
                ed.on('change', function(e) {
                    console.log('the content ', ed.getContent({ format: 'text' }));
                });
            }
        };
    [![tinymce.init(editor_config);][1]][1]

when test this setting, console output only "call video".



via Chebli Mohamed

convert unix time and pass it to blade

i have this json file

  0 => array:8 [▼
"time" => 1532476800
"close" => 8170.23
"high" => 8481.11
"low" => 8061.07
"open" => 8395.81
"volumefrom" => 89988.19
"volumeto" => 736530740.43

i want to convert time from uinx time to real time and pass all this valus to blade to add it in candle chart

and this my blade javascript

  "dataProvider": [ $date,$high,$close,$low,$open ], // this example of what i want to do 



via Chebli Mohamed

Laravel - two factories refer to each other

I have an existing database, what is not modifiable. My current job is to make factories.

In the present case I have two tables. One is the item table, and the other is the item_image table.

An item has many images, but the featured-image-id stored in the item.

Here is my two factories:

Item factory

$factory->define(Item::class, function (Faker $faker) {
   return [
    'title' => $faker->words(3, true)
    'user' => function () {
      return factory(User::class)->create()->id;
    },
    'featured_image' => function () {
      return factory(Image::class)->create()->id;
    },
  ];
});

ItemImage factory

$factory->define(Image::class, function (Faker $faker) {
  return [
    'item' => function () {
      return factory(Item::class)->create()->id;
    },
  ];
});

item.featured_image column:

  • FK -> item_image.id
  • Not NULL

item_image.item column:

  • FK -> item.id
  • Not NULL

For example, when I want to create an item, the item factory refers to the itemImage factory, which would create an item that would create an image. bla bla bla. It cause an infinity loop.

How should i rewrite these factories?

Thanks for the help.



via Chebli Mohamed

How to stream an large file from S3 to a laravel view

I have this mostly working but having a tough time finalizing it.

For now I have a simple route:

Route::get('file/{id}/', 'FileController@fileStream')->name('file');

this route connects to an action in the FileController:

public function fileStream($id){

    $audio = \App\Audio::where('id', $id)->first();

    $client = S3Client::factory([
        'credentials' => [
            'key'    => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
        ],
        'region' => env('S3REGION'),
        'version' => 'latest',
    ]);


    // Register the stream wrapper from an S3Client object
    $client->registerStreamWrapper();

    if ($stream = fopen('s3://[bucket_name]/'. $audio->audio_url, 'r')) {
        while (!feof($stream)) {
            echo fread($stream, 1024);
        }
        fclose($stream);
    }    
}

This works to the browser: if I go to a url: /file/1 it looks up the right file, and in a clean browser window I get:

enter image description here

And then in my view I am trying to output the audio like:

   <audio>
      <source src="" type=""></audio>
   </audio>

But no player is getting output to the screen.

TIA



via Chebli Mohamed

Comparing Attribute in Laravel Eloquent Request

I have a controller function where I would like to compare a field in a model to an attribute of that model and use it in a where like so below, is it possible?

$ticketsOpen = Ticket::where([
                 ['balance','>','paidBalance'],
                 ['bill_to', $customer->id]
                 ])
                  ->whereNotIn('shipment_billing_status', [2,3])
                  ->orderBy('created_at','desc')->get();

In this case, the 'paidBalance' up above refers to this in the model:

public function getPaidBalanceAttribute(){
    $paid = $this->paymentDistributions->pluck('amount');
    $paidBalance = $paid->sum();
    return $paidBalance;
}

And the paymentDistributions refers above that to this:

 public function paymentDistributions(){
        return $this->hasMany('App\Payments_Distribution', 'ticket_id','id');
    }

Or is there a better way of going around this? I'm just trying to filter down the tickets that have a balance greater than what's been paid or have no payments toward the ticket at all.

Thanks!



via Chebli Mohamed

Laravel 5.6 get user in Routes issue

How to get an id of the user?

Route::group(['middleware' => 'auth'], function()
{
    var_dump(Auth::user());
}

It returns null.

Simple things made difficult.. Also there is no reliable explanation

How to handle this?



via Chebli Mohamed

What is Laravel Broadcasting Authentication Approach

I wanted to know how laravel handles authentication using websockets ? I know that by default websocket protocol doesn't come with any authentication mechanism , so I've seen people check user authentication while creating socket, I mean they check user token or cookie or ..., on handshake http request. I want to know how laravel handle this issue.



via Chebli Mohamed

Serialize the Form dynamic image field using ajax in laravel 5.6

Hi i want to serialize the form using ajax in laravel but i'm getting the error i don't know why trying hard on searching the internet but not able to understand what is the error and what is the real problem .

Here is my view

<html lang="en">
<head>
    <meta name="_token" content="" />
    <title>Laravel Multiple File Upload Example</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    @if (count($errors) > 0)
        <div class="alert alert-danger">
            <strong>Whoops!</strong> There were some problems with your input.<br><br>
            <ul>
                @foreach ($errors->all() as $error)
                    <li></li>
                @endforeach
            </ul>
        </div>
    @endif

    @if(session('success'))
        <div class="alert alert-success">
            
        </div>
    @endif

    <h3 class="jumbotron">Laravel Multiple File Upload</h3>
    <form method="post"  id="d-form" enctype="multipart/form-data">
        

        <div class="input-group control-group increment" >
            <input type="file" name="filename[]" class="form-control">
            <input type="text" name="descri[]" class="form-control">
            <div class="input-group-btn">
                <button class="btn btn-success" type="button"><i class="glyphicon glyphicon-plus"></i>Add</button>
            </div>
        </div>
        <div class="clone hide">
            <div class="control-group input-group" style="margin-top:10px">
                <input type="file" name="filename[]" class="form-control">
                <input type="text" name="descri[]" class="form-control">
                <div class="input-group-btn">
                    <button class="btn btn-danger" type="button"><i class="glyphicon glyphicon-remove"></i> Remove</button>
                </div>
            </div>
        </div>

        <button type="submit" class="btn btn-primary" style="margin-top:10px">Submit</button>

    </form>
</div>


<script type="text/javascript">
    $(function() {
        $.ajaxSetup({
            headers: {
                'X-XSRF-Token': $('meta[name="_token"]').attr('content')
            }
        });
    });

    $(document).ready(function() {

        $(".btn-success").click(function(){
            var html = $(".clone").html();
            $(".increment").after(html);
        });

        $("body").on("click",".btn-danger",function(){
            $(this).parents(".control-group").remove();
        });
        $("#submit").submit(function(){
            var formdata = $("#d-form").serialize();
            $.ajax({
                type: 'POST',
                url: '/form',
                data: formdata,
                success: function (data) {
                    alert(data);
                },
            });
            stay.preventDefault();
        });

    });



</script>
</body>
</html>

Here is my controller in which i'm getting the images and saving it using json.

<?php

namespace App\Http\Controllers;
use App\Form;
use Illuminate\Http\Request;

class FormController extends Controller
{
    public function create(Request $request)
    {
        $this->validate($request, [
            'filename' => 'required',
            'filename.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
        ]);
        return view('create');
    }
    public function store(Request $request)

    {

        $this->validate($request, [

            'filename' => 'required',
            'filename.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'

        ]);

        if($request->hasfile('filename'))
        {

            foreach($request->file('filename') as $image)
            {
                $name=$image->getClientOriginalName();
                $image->move(public_path().'/images/', $name);
                $data[] = $name;
            }
        }

        $form= new Form();
        $form->filename=json_encode($data);


        $form->save();

        return  "Your images has been successfully";
    }
}

Finally here is my routes.

Route::get('form','FormController@create');
Route::post('form','FormController@store');



via Chebli Mohamed

CD Laravel Maintenance Mode Fails when missing dependency file

I'm working with CircleCi (a great continuos integration and delivery platform). In my configuration file for the deployment job I have the following process.

  1. Enable Maintenance Mode
    php artisan down --message="Update in progress" --retry=30
  2. Checkout Branch
  3. Install Dependencies
  4. Webpack Compilation
  5. Run Migrations
  6. Disable Maintenance Mode
    php artisan down

The idea is that enabling maintenance mode fist, if some step fails then the application stays down. But I faced that I can´t setup maintenance mode when missing dependencies. I'm getting this:

In ProviderRepository.php line 208:
  Class 'Spatie\GoogleCalendar\GoogleCalendarServiceProvider' not found

So why I can't set maintenance when some provider (that has nothing to do with this) is not found. Has not sense to me.
Is out there any workaround to this? Like setting up the mode without running the artisan command? Should I report it to the framework contributors? Or am I missing something?



via Chebli Mohamed

Ubuntu Server 16.04.5 installed with Apache loads Laravel application as plain text

I have deployed Laravel 5.5 application on Ubuntu Server and I keep getting plain text when I load the index.php in public folder of my application. I think there is something wrong with the server configuration or I might be missing an extension or dependency. Any help please.



via Chebli Mohamed

How to redirect a view if session exist? (Laravel)

I want to make view can't be loaded if session is exist and redirect it to other view. For example if user is logged in (session exist), the login page view should redirect to main page instead. Currently my code is like this. This code can detect the session but redirect is not working (blank page).

<?php if (Session::has('sessionId')){return redirect('/front')} ?>
<!DOCTYPE html>
<html>
</html>



via Chebli Mohamed

Laravel Errors field is required

hi i have a problem that the error message is not showing the field name and its only showing the errorfor the first field not for all the fields

here is the code

 public function store(Request $request)
{
    //validate
    $this->validate($request,[
       $request->name=>'required',
       $request->type=>'required',
       $request->color=>'required',
        $request->about=>'required|min:10'
    ]);

 //   create a car
    $car = new Car();
    $car->user_id=auth()->user()->id;
    $car->name=$request->name;
    $car->type=$request->type;
    $car->color=$request->color;
    $car->about=$request->about;

    $car->save();

    return redirect('home')->with('success','Done The Car is added');
}

here is the messages.blade.php

@if(count($errors)>0)
@foreach($errors->all() as $error)
    <div class="alert alert-danger"></div>
@endforeach @endif

@if(session('success'))
<div class="alert alert-success">
    
</div>@endif



via Chebli Mohamed

Laravel | Get value of a column with

i am having a problem with laravel, all the details are given below.

I Have 2 tables in mysql database : books & pens.

books & pens have columns : bookid,bookname & penid,penname, respectively.

Users have a transactions table with : bookid or penid.

I am retrieving all the transactions of a specific user with this:

$usertransactions = $user->usertransactions;

Not to worry about the relationships between user and usertransaction model, its all setup.

the response of the function above is:

"data": {

    "Id": "1",
    "Bookid": "27",

}

or

"data": {

    "Id": "2",
    "Penid": "42",

}

I want the result to be like below:

"data": {

    "Id": "1",
    "Bookid": "27",
    "Bookname" : "bookname from books table using the Bookid from response"

}

I Would appreciate the help.

Regards



via Chebli Mohamed

REQUEST_DENIED for google geocoding API

 geocoder.geocode({ 'address': address }, function (results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        var latitude = results[0].geometry.location.lat();
        var longitude = results[0].geometry.location.lng();
        document.getElementById('latitude').setAttribute('value', latitude);
        document.getElementById('longitude').setAttribute('value',  longitude);
        var lat = parseFloat(latitude);
        var lng = parseFloat(longitude);
        var latlng = new google.maps.LatLng(lat, lng);
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({ 'latLng': latlng }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[1]) {
                    document.getElementById('physicaladdress').setAttribute('value', results[1].formatted_address);
                }
            }
        });
    } else {
       console.log(""+status);
    }
});

This is my javascript file where i am trying to get latitude and longitude from zip code ,it is working fine in localhost but not when it is hosted live(say aws)

{} ,this i am giving into the app.blade.php , any help would be much appreciated sorry if i am missing anything while asking question.



via Chebli Mohamed

Order by distance on POINT in Laravel 5.1 via associated tables

I'm attempting to order events by their distance from a user submitted postcode and distance.

I've attached a sample of my database tables and their relationships, as you can see geom is associated with multiple addresses via postcode and addresses can be associated to multiple tables (in this instance the events table).

Sample Database Tables

I'm taking a postcode from the end user as well as a radius in miles to retrieve appropriate events, here is a sample of how I am achieving this in Eloquent.

/**
 * Extend locale method which initially only gets lat/long for given postcode to search
 *
 * @param \Illuminate\Database\Eloquent\Builder $query The query builder
 * @param \App\Http\Requests\SearchRequest $request The search request
 * @return void
 */
protected function locale(Builder $query, SearchRequest $request)
{
    $postcode = $this->formatPostcode($request->postcode);

    $geom = Geom::query()->where('postcode', $postcode)->first();
    if (! $geom || Cache::has('postcodeAPIFailed')) {
        return;
    }

    $lat = $geom->geo_location['lat'];
    $long = $geom->geo_location['long'];

    // Top-left point of bounding box
    $lat1 = $lat - ($request->within / 69);
    $long1 = $long - $request->within / abs(cos(deg2rad($lat)) * 69);

    // Bottom-right point of bounding box
    $lat2 = $lat + ($request->within / 69);
    $long2 = $long + $request->within / abs(cos(deg2rad($lat)) * 69);

    $query->whereHas('address', function (Builder $query) use ($request, $lat, $long, $lat1, $long1, $lat2, $long2) {
        $query->whereHas('geom', function (Builder $query) use ($request, $lat, $long, $lat1, $long1, $lat2, $long2) {
            $query->whereRaw('st_within(geo_location, envelope(linestring(point(?, ?), point(?, ?))))', [$long1, $lat1, $long2, $lat2]);
        });
    });
}

In the controller after we have retrieved the search results, we calculate the distances for each of the results.

if ($request->has('postcode')) {
    $postcodeDistances = $this->getDistances($results, $request);
}

This produces an array with a key of postcode and value of distance, i.e $postcodeDistances['L1 0AA'] = '3';, we send this array to the view.

In the view we then use the following logic to display distance on a record where applicable

@if($postcodeDistances)
    <span>
        
        mile away
    </span>
@endif

I've tried a few methods but I've been unable to update my function locale() to do the ordering by distance. I've considered maybe I can attached the distance to the collection and use a Laravel method to order the collections that way but achieving this from the database layer would be ideal if the latter is even possible.

My first attempt was to addSelect a distance field after whereHas('geom') and order by the new field

$query->addSelect(\DB::raw("ST_DISTANCE_SPHERE(geo_location, POINT({$long}, {$lat})) AS distance"));

I receive the following error:

SQLSTATE[21000]: Cardinality violation: 1241 Operand should contain 2 column(s) (SQL: select count(*) as aggregate from `event` where (select count(*) from `address` where `address`.`addressable_id` = `event`.`id` and `address`.`addressable_type` = event and (select count(*), ST_DISTANCE_SPHERE(geo_location, POINT(-2.717472, 53.427078)) AS distance from `geom` where `geom`.`postcode` = `address`.`postcode` and st_within(geo_location, envelope(linestring(point(-3.6903924055016, 52.847367855072), point(-1.7445515944984, 54.006788144928))))) >= 1) >= 1 and (select count(*) from `organisation` where `event`.`organisation_id` = `organisation`.`id` and `status` = 1) >= 1 and `event_template_id` is not null and `date_start` >= 2018-07-31 00:00:00 and `status` in (1, 5))

I also attempted to use orderByRaw in the same place instead, whilst I did not receive an error the results were not ordered accordingly.

$query->orderByRaw('ST_DISTANCE_SPHERE(geo_location, POINT(?, ?)) ASC', [$long, $lat]);



via Chebli Mohamed

S3 creates blank transparent webp image

I have uploaded webp image into Amazon-S3. But sometimes it generates a blank transparent webp image. Content-Type:image/webp and file-size are also correct. 
Also, note that it displays from the mobile application but not in any browser. All is working fine on the local server. 
Problems occur in only with the live server. I've used the following code

$disk = Storage::disk('s3');
$original_targetFile = "videoflyer/webp_original/" . $image;
$disk->put($original_targetFile, file_get_contents($original_sourceFile), 
'public');  

S3 generates a blank image like this:  https://videoflyer.s3.us-east-2.amazonaws.com/videoflyer/webp_original/5b14e4b57da79_json_image_1528095925.webp

Anybody can help me to resolve this issue?



via Chebli Mohamed

where is the blade file of the reset password?

in laravel 5.6

I used the following command to generate auth files:

php artisan make:auth

but I can not find the blade.php file used for reset password email to edit it.

where is it?



via Chebli Mohamed

Get different content from same URI

I am developing a blog system using Laravel and showing content based on URI segment. My segment is 3 and this segment is, post TITLE.

Problem is once a post title is "test" and another post has same title, "test" then system is showing only 1 post where there are 2 post actually.

How could I show the both post with same URI.

Example: URI : example.com/article/test Expected Content : Test1 Test1 Test1 Test1 Test1 Test1 Test1 Test1 Test1 Test1 Test1 Test1 Test1 Test1 Test1 Test1 Test1 Test1 Test1 Test1 Test1 Test1 Test1 Test1

Example: URI : example.com/article/test Expected Content : Test2 Test2 Test2 Test2 Test2 Test2 Test2 Test2 Test2 Test2 Test2 Test2 Test2 Test2 Test2 Test2 Test2 Test2 Test2 Test2 Test2 Test2 Test2 Test2



via Chebli Mohamed

What does "bindings" middleware do in Laravel 5.6?

Just as per the title. Default api middleware in Laravel 5.6 is listed in Kernel.php as:

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

I'd appreciate a layman's explanation of what bindings does, which I can't find anywhere in the docs or on the internet?



via Chebli Mohamed

How to make pagination in Laravel 5.2 when the URL length exceeds its limit

I am working on a project with Laravel 5.2 I have hidden ID values and I want to search the ID from the database and later I will sort it in descending order. I wrote this code.

Controller

$jsonObject =json_decode(request('membersdata'));
$member = (new Membermasternewdata)->newQuery();
$members=$member->whereIn('id', $jsonObject)->latest();
$members=$members->paginate(50);

View The html page



My URL example http://localhost:8000/ascendingregistrationdate?_token=ktlNHgx9PLNCOQL0CE1YZT2AzmWpJeXexqOduy8F&membersdata=%5B199%2C284%2C344%2C355%2C381%2C461%2C488%2C576%2C601%2C652%2C747%2C825%2C849%2C878%2C883%2C912%2C913%2C915%2C972%2C1004%2C1071%2C1310%2C1501%2C1534%2C1585%2C1610%2C1677%2C1854%2C1923%2C1935%2C2163%2C2301%2C2302%2C2326%2C2339%2C2717%2C2773%2C3052%2C3361%2C3446%2C3683%2C3848%2C3853%2C3914%2C4114%2C4244%2C4311%2C4357%2C4389%2C4881%2C5312%2C5322%5D&page=2

I got a problem with pagination. For around 400 records, the pagination works. But If I have many records, pagination doesn't work as the URL length exceed its limit.  Is there any workaround for this problem?

Thank you!



via Chebli Mohamed

Boolean not set to true

There are two tables "Stock" and "Soldstock".

Table stock contains all the stocks that have been added. Im trying to add the stocks that are sold to the SoldStock table. the stock table is shown below:

Schema::create('stocks', function (Blueprint $table) {            

  $table->increments('tag_no');   
  $table->boolean('sold')->default(0);           
  $table->integer('user_id')->unsigned();
  $table->foreign('user_id')->references('id')->on('users');
  $table->timestamps();            
});

So when i add the stocks to SoldStock table .. im trying to find that stock with that tag_no and change its sold boolean to true. But its not working! Below is the store function.

public function store(Request $request)
{

        if(Auth::check()){
            if (SoldStock::where('tag_no','=',$request->input('tag_no'))->exists()) { 
                return back()->withInput()->with('errors', 'Tag number already entered!');                
                }      

            $soldstock = SoldStock::create([
                'tag_no' => $request->input('tag_no'),                
                'user_id' => Auth::user()->id
            ]);               

            $stock = Stock::where('tag_no','=',$request->input('tag_no'))->first();            
            if($stock){
                $stock->sold=1;        
                error_log($sell->sold);                           
                return redirect()->route('soldstock.index', ['stocks'=> $soldstock->tag_no])
                ->with('success' , 'Stock added successfully');
            }                
        }        
        return back()->withInput()->with('errors', 'Error adding Stock');     
    }

I use this to find the stock:

$stock = Stock::where('tag_no','=',$request->input('tag_no'))->first();

and to change its sold boolean to true i use this:

$stock->sold=1; 

But its not working.



via Chebli Mohamed

Laravel Mix Notification on Docker - NO NOTIFICATION DISPLAY

I'm having a Laravel Project and I run it using Laradock. Also I added vue js components on it and run npm run dev or npm run watch to compile every changes I made but now it didn't display any Laravel Mix Notification whenever I try to compile.

Before I use xampp and the notification works fine. I just happened to know that using Docker in my project is great.

If anyone knows how to make my Laravel Mix Notification work again in Docker. Thanks!



via Chebli Mohamed

Consume own API from linked bot

I'm looking to do the following, but have not been able to conceptualize the required steps to make this work:

  • I have a user sign-up to my website using default Laravel Auth (table: users)
  • I then want the user to connect/link their messenger account (e.g. Telegram or FB Messenger) to that website account. (table: services_users)
  • Once linked and verified, I want the user to be able to send commands that consume the website APIs under that linked user account.

In the http request (get) I will need to send some kind of bearer token, but I am unsure how, when and where to create and set this. I've tested creating a Personal Access Token, which works, but I can't imagine it is good practice to store that PA token in the database.

Any guidance is much appreciated. Thanks!



via Chebli Mohamed

Deleted method is still executed even though it's not existing anymore Vue.js

Does anybody here experienced deleting a method in vue.js but is still triggered or executed during run-time? I have a button before and assigned a method to trigger or execute:

<div>
     <ui-button raised @click="search()">Search</ui-button>
</div>

methods:{
    search(){
        //search this and that
    }
}

But in the long run of our development, we deleted the method and replace it with a new one.

<div>
     <ui-button raised @click="dothisInstead()">Search</ui-button>
</div>

methods:{
    dothisInstead(){
        //search this and that
    }
}

And that works very well. But just this day, if we click the search button, it's looking for the search() method and executing its lines even though it's non-existent and now it throws error.

I have tried clearing my cache, restarting my PC, restarting my compiler and XAMPP and nothing has changed. Then I also tried composer dump-autoload and works. And just this moment, the error came back and dump-autoload is not fixing it. Any idea how to resolve this? I'm really stuck on this and can't proceed with my next step.



via Chebli Mohamed

No query results for model at boot created event

I have a model with boot function which has created event like below.

However, I sometimes (not all the time) get No query results for model on ProcessAddressRefine which is a job. As far as I understand, created event should happen after record is created, so there is no way that there is no query result unless it gets deleted right after it has been created. I also wonder that looking at the DB record, ProcessAddressRefine job is properly executed.

What would be the problem in this case?

Any advice or suggestion would be appreciated. Thank you.

public static function boot()
{
    parent::boot();

    self::created(function ($model) {
        if (!$model->lat || !$model->lng) {
            ProcessAddressRefine::dispatch($model);
        }
    });
}



via Chebli Mohamed

Laravel 5 Error occurs while inserting into sql table with sequence_id

I am trying to insert data to oracle sql and nothing happened but this error message

Error Code : 1722 Error Message : ORA-01722: invalid number Position : 162 Statement : insert into SLS_test (call_id, phone_number, operator_name, call_comment, complaint, spon_id, technical, served, serve_comment, call_time, serve_time) values (:p0, :p1, :p2, :p3, :p4, :p5, :p6, :p7, :p8, :p9, :p10) Bindings : [call_id_seq.nextval,call_id_seq.nextval,996,996,asd,asd,asd,asd,asd,asd,asd,asd,0,0,0,0,asd,asd,2018-07-31 16:09:09,2018-07-31 16:09:09,2018-07-31 16:09:09,2018-07-31 16:09:09]


My WelcomeController.php :

public function create(Request $req)
{
    $phone_number = $req -> input('phone_number');
    $operator_name = $req -> input('operator_name');
    $call_comment = $req -> input('call_comment');
    $complaint = $req -> input('complaint');
    $spon_id = $req -> input('spon_id');
    $technical = $req -> input('technical');
    $served = $req -> input('served');
    $serve_comment = $req -> input('serve_comment');
    $ctime = new DateTime();
    $stime = new DateTime();
    $data = array("call_id" => "call_id_seq.nextval" , "phone_number"=>$phone_number,"operator_name"=>$operator_name,"call_comment"=>$call_comment,"complaint"=>$complaint,"spon_id"=>$spon_id,"technical"=>$technical,"served"=>$served,"serve_comment"=>$serve_comment,"call_time"=>$ctime,"serve_time"=>$stime);
    DB::table('test')->insert($data);
}



via Chebli Mohamed

Cannot create foreign key

I want to create a foreign key that is string from table "stocks" to "rfids". The two tables are shown below. stocks table:

Schema::create('stocks', function (Blueprint $table) {            

        $table->increments('tag_no');                       
        $table->string('stock_type');

        $table->string('rfid');
        $table->foreign('rfid')->references('RFID_UID')->on('rfids');

        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');

        $table->timestamps();            
    });

rfids table:

Schema::create('rfids', function (Blueprint $table) {            

        $table->increments('id');
        $table->string('RFID_UID');

        $table->timestamps();
    });

When i use php artisan migrate it shows error.

SQLSTATE[HY000]: General error: 1005 Can't create table hardware.#sql-81c_c8 (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table stocks add constraint stocks_rfid_foreign foreign key (rfid) references rfids (RFID_UID))

Someone help me pls!



via Chebli Mohamed

lundi 30 juillet 2018

How to add / remove elements from array that is in Request

My request looks like this

Array
(
  [name] => Eugene A
  [address] => Array
    (
        [billing] => Array
            (
                [address] => aaa
            )
        [shipping] => Array
            (
                [address] => bbb
            )
    )
)

I need to delete the shipping address. But how?

I can only delete both addresses,

$request->request->remove('address');

but I don't want it.

I want to delete only shipping address, like so

$request->request->remove('address.shipping');

But it is not working for me

Laravel 5.6



via Chebli Mohamed

how to define a named route and download a file from database in laravel

I have my url defined in blade as:

href="/finance/invoices/download/"

and the route in web.php is:

Route::get('invoices/download/{year}/{month}/{file}', 'InvoiceController@download');

my file is stored in the database as:

2018/07/invoiceberry_invoice_template_1.docx

edit function in my controller is:

public function edit(Invoice $invoice)
{
    $projectStageBillings = $invoice->projectStageBillings;

    $projectStageBilling = $projectStageBillings->first();
    $client = $projectStageBilling->projectStage->project->client;
    $client->load('projects', 'projects.stages', 'projects.stages.billings');

    $billings = [];
    foreach ($projectStageBillings as $key => $billing) {
        $billing->load('projectStage', 'projectStage.project');
        $billings[] = $billing;
    }

    return view('finance.invoice.edit')->with([
        'invoice' => $invoice,
        'clients' => Client::select('id', 'name')->get(),
        'invoice_client' => $client,
        'invoice_billings' => $billings,

    ]);
}

and download method is :

public function download($year, $month, $file, $inline = true)
{
    $headers = [
        'content-type' => 'application/pdf',
    ];

    $file_path = FileHelper::getFilePath($year, $month, $file);

    if (!$file_path) {
        return false;
    }

    if ($inline) {
        return Response::make(Storage::get($file_path), 200, $headers);
    }

    return Storage::download($file_path);
}

how do I do that?



via Chebli Mohamed

htmlspecialchars() expects parameter 1 to be string, object given

This is Controller. I named it CartController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Gloudemans\Shoppingcart\Facades\Cart;
use App\Product;

class CartController extends Controller
{

public function index()
{
    $cartItems=Cart::content();
    return view('cart.index', compact('cartItems'));
}

public function edit($id)
{
    $product=Product::find($id);

    Cart::add($id,$product->name,'1',$product->price);
}

This is my welcome.blade.php. This is the page where I display all my Items.

<div class="row">
@forelse($books->chunk(4) as $chunk)
  @foreach($chunk as $book)
    <div class="column-prod">
<a href="">
<div class="card-prod">
<center><img src=""  style="width: 300px; height: 300px;"></center> </a>
  <div class="container-prod">
    <h2></h2>
    <p class="title"></p>
    <p class="price">₱ </p>

    <p><a href="" class="button"><i class="fas fa-cart-arrow-down"></i>Add to Cart</button></a></p>
    <p><button class="button"><i class="fas fa-heart"></i>  Add to Wishlist</button></p>
  </div>
  </div>
</div>

@endforeach 
@empty
<h3> No Books </h3>
@endforelse 


 </div> <!--Div all end-->

This is the codes of my Cart Page. When the user click add to cart in the welcome page, his/her chosen items will be place in this page.

  <h3> Cart Items </h3>

  <!--TABLE NAMESSS-->
                    <table class="table table-hover">
                        <thead>
                            <tr>
                               <th scope="col">Image</th>
                               <th scope="col">Name</th>
                               <th scope="col">Price</th>
                               <th scope="col">Quantity</th>

                            </tr>
                        </thead>


            <tbody> 
                @foreach($cartItems as $cartItem)
                <li></li>
                    <tr>

                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>

                    </tr>
                @endforeach
            </tbody>
        </table>

This is my route.

Route::get('/', function () {
return view('welcome')->with(['books' => \App\Product::all()]);
});

Route::get('/cart','ShopController@cart');

Route::get('/signin','ShopController@signin');



Route::resource('/cart','CartController');

Route::get('/wishlist','ShopController@wish');



Auth::routes();

Route::get('/logout', 'Auth\LoginController@logout');

Route::get('/home', 'HomeController@index');

Route::group(['prefix' => 'admin', 'middleware' => 'auth'], function(){
        Route::get('/',function(){
            return view('admin.index');
        })->name('admin.index');


        Route::resource('product','ProductsController');
        Route::resource('category','CategoriesController');
});

Route::get('/categ', function(){
return view ('admin.category.categ_index');

});

I'm confused I don't know how to fix my error. This is the complete error that the system return.

"htmlspecialchars() expects parameter 1 to be string, object given (View: C:\xampp\htdocs\Shop\resources\views\welcome.blade.php)"

I hope you can help me in solving this. Your answers are very much appreciated.



via Chebli Mohamed

Laravel 5.6 share auth id issue

I want to pass user id in the boot function of the AppServiceProvider class (as it written in the docs) but for some reason Auth::user() object is empty.

myAppName/app/Providers/AppServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\URL;

use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Auth;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Schema::defaultStringLength(191);
        URL::forceScheme('https');
        View::share('user_info', Auth::user());
    }

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

And then in in some blade template:

<p></p>

As a result an error occurs:

Trying to get property 'id' of non-object

There is same error if want to pass Auth::user()->id

How to make it work?



via Chebli Mohamed

Implement a Repository Interface into Job

I am trying to implement an Interface into a Job but having no luck. Is it possible to implement an interface / repository within the public construct and use said interface in the handle() method of the Job?

The error I am getting is as follows:

Argument 1 passed to App\Jobs\OrderCreate::__construct() must be an instance of App\Http\Interfaces\OrderInterface, string given, called in /Users/Panoply/Sites/stock-sync/app/Http/Controllers/StockController.php on line 31

Below is a basic setup of what I am trying to achieve.

Stock Controller:

public function test(){
   dispatch(new OrderCreate('hello'));
}

OrderCreate Job:

protected $order;
protected $test;

public function __construct(OrderInterface $order, $test)
{
    $this->order = $order;
    $this->test = $test;
}

public function handle()
{
    $this->order->test($this->test);
}

OrderRepository:

class OrderRepository implements OrderInterface
{
    public function test($data) {
        error_log($data);
    }
}

OrderInterface:

public function test($data);

I have had no troubles implementing this pattern into my controllers and commands but I can't seem to get it working on a Job.



via Chebli Mohamed

Laravel ignores onDelete('restrict')

$table->foreign('applicationstatus_id')->references('id')->on('applicationstatuses')->onDelete('restrict');

I have the above line in my applications table but its ot restricting delete, it goes on and deletes the record. This is Laravel. Please help.



via Chebli Mohamed

Laravel fetching JSON column dollar sign

Im trying to fetch some datas depending on the JSON column meta. However, something weirds happen around the -> symbol.

File::whereJsonContains('meta->serie', 'value')->toSql();

output

"select * from `files` where json_contains(`meta`->'$.\"serie\"', ?)"

Here is the error I get

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '>'$."serie"', ?)' at line 1 (SQL: select * from files where json_contains(meta->'$."serie"', "check_up"))

I tried using a regular where but it throws the same error. Any idea?



via Chebli Mohamed

Invalidate JWT Token only after a period of inactivity

I'm using Tymon JWT package in my Laravel project, and I need to invalidate the token of the connected user after 4 hours of inactivity. In the config file of the package I can set the TTL time for a token as : 'ttl' => env('JWT_TTL', 240), and the user will be logged out every 4 hours even if he was active, but I only want that to happen if the user wasn't active during the whole 4 hours.



via Chebli Mohamed

Laravel 5.6 authentication with JWT and ADLDAP

I have both my ldap server set up (with adldap2/adldap2-laravel) and my JWT set up (with tymon/jwt-auth) for a SPA built with Vue/Vuetify and Laravel api backend. The JWT is all set up to the point where if I leave my provider as eloquent, I can get a successful login attempt with my eloquent users:

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ]
],

As soon as I change the driver to adldap and attempt a username/password that is known to be valid in our ldap system, I am stuck on an unauthorized error. Does anyone have any advice or resources to marry these two? I know that there are a lot of differences with laravel/passport sessions and JWT, but I'm not seeing a simple solution. Here is my AuthController:

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class AuthController extends Controller
{
    use AuthenticatesUsers;

    /**
     * Create a new AuthController instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('jwt', ['except' => ['login']]);
    }

    public function login()
    {
        $credentials = request(['username', 'password']);

        if (! $token = auth()->attempt($credentials)) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        return $this->respondWithToken($token);
    }

    public function me()
    {
        return response()->json(auth()->user());
    }

    public function logout()
    {
        auth()->logout();

        return response()->json(['message' => 'Successfully logged       out']);
    }

    public function refresh()
    {
        return $this->respondWithToken(auth()->refresh());
    }

    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth()->factory()->getTTL() * 60,
            'user' => auth()->user()->name
        ]);
    }
}



via Chebli Mohamed

Laravel 5.5 - Private folder access

I use Laravel filemanager (UniSharp) to manage my files. I put everything in storage. I created a public and a private path inside shares folder.

I tried to create routes but it seems that Filemanager overwrite my routes ? And Auth helper doesn't work in filemanager src files ...

How can I set private path realy private (for auth users) ?

Thanks.



via Chebli Mohamed

i use jwt with laravel project how i want cancel token expiration because i want use it in api and save token in database

this is config.php to jwt how i can do it

'ttl' => 60,

/*
|--------------------------------------------------------------------------
| Refresh time to live
|--------------------------------------------------------------------------
|
| Specify the length of time (in minutes) that the token can be refreshed
| within. I.E. The user can refresh their token within a 2 week window of
| the original token being created until they must re-authenticate.
| Defaults to 2 weeks
|
*/

'refresh_ttl' => 20160,

**i need it because android developer save token in file and when the user login Times coming After the first login the application send token If it exists in the file send it to server and Check it in the database and return user information without login if not exists must login can i do this or i need another way to do it **



via Chebli Mohamed

Laravel 5.4 : TokenMismatchException in VerifyCsrfToken.php line 68

When sending a post request When you send a query post, an error occurs TokenMismatchException in VerifyCsrfToken.php line 68.

{!! Form::open( ['route'=>'import.store', 'method'=>'POST', 'class'=>'form-horizontal form-label-left', 'files' => true]) !!}
 {!! Form::label('path', 'Seleccione archivo:', ['class'=>'control-label col-md-3 col-sm-3 col-xs-12']) !!}
 {!! Form::file('path',['required'=>'required', 'class'=>'btn btn-default'])!!}
 {!! Form::submit('Validar', ['class'=>'btn btn-info', 'id'=>'validar', 'name'=>'validar']) !!}
 {!! Form::submit('Cargar', ['class'=>'btn btn-success', 'id'=>'cargar', 'name'=>'cargar']) !!}
{!! Form::close() !!}

html generate

.ENV FILE

APP_ENV=local                                                  
APP_DEBUG=true                                                 
APP_KEY=base64:wMmIEY6XqQu7nbnIRmuURxrKj6V5EL/XCel9xX50/RQ=    
APP_URL=g200603sv07q                                           

DB_CONNECTION=mysql                                            
DB_HOST=localhost                                              
DB_PORT=3306                                                   
DB_DATABASE=encuestas                                          
DB_USERNAME=usr_pro                                            
DB_PASSWORD=Cenco2301.                                         

CACHE_DRIVER=file                                              
SESSION_DRIVER=file                                            
SESSION_DOMAIN=                                                
QUEUE_DRIVER=sync                                              

REDIS_HOST=127.0.0.1                                           
REDIS_PASSWORD=null                                            
REDIS_PORT=6379                                               

My import controller

public function store(Request $request)
{
    $path = $request->file('path');
    $finfo = finfo_open(FILEINFO_MIME);
    $mime = finfo_file($finfo, $path);
    finfo_close($finfo);
    $extension = substr($path->getClientOriginalName(),-3);
    if ($mime=='text/plain; charset=iso-8859-1' && $extension=='csv') {
        $upload = $path->store('csv');
        if ($request->input('validar')) {
            DB::Statement('CREATE TEMPORARY TABLE datatemps LIKE data');
            $this->validar($path);
            flash('Archivo puede ser procesado, se encontraron '.$this->countfiles.' registros')->success();
        }
        elseif ($request->input('cargar')) {
            $this->guardar($path);
            flash('Archivo procesado, se han subido '.$this->countfiles.' registros')->success();
        }
    }
    else {
        flash('Archivo no valido')->error();            
    }
    return view('admin.import');
}

Operating System: CENTOS 7 Laravel 5.4.36 php 7.1



via Chebli Mohamed

Laravel 5.6 shared auth user info issue

I'am trying to set variable with info of authenticated user (id, name, image, e.t.c) but still have a problem with that. I've already checked about 10 examples but none of them work. At least I've tried this one approach but it doesn't work.

Use of undefined constant userinfo

So I didn't find full working example how to set variable with user info globally. Every single example is related to the old versions of Laravel or not described well or doesn't work. So I have to test every pice of code if it works. Also there is so many variants and middleware stuff (which is not described almost or terribly as you might already guess) and it is overwhelming.

It seems that I have to do something with middleware in case to use varibale globally but I suppose the problem is that not many people knows how it actually works in Laravel so that there is a large variety of methods in the internet and many of them are crutches or for old versions.

Is there simple way (that just works!) to set user info in one place and get it in any controller or blade temple?



via Chebli Mohamed

Laravel logout function is not working

I am creating a project using laravel as the backend and angular 5 angular 5 as the front end. While accessing laravel functions through API calls from angular for logout it gives an error message

exception:"BadMethodCallException"

file: "/path/vendor/laravel/framework/src/Illuminate/Support/Traits/Macroable.php" line:96 message:"Method logout does not exist."

public function getlogout() {

        if (Auth::logout()) {
            return response()->json(['status' => true, 'message' => 'Successfully logged out']);
        }
}

please, someone, help me as I am new to laravel.



via Chebli Mohamed

How to change config variable

I created a router where I output config information

dd config

I'm trying to change value from .env file, for example APP_NAME, from APP_NAME="Nuxt + Laravel" to APP_NAME="test" but the change is not displayed on the page!(of course I reloaded the page 😊)

I was trying to look through php artisan tinker tinker

It works! But my config remains the same. I can not solve this problem for a week now.

I cleared the cache!!! I tried php artisan cache:clear, php artisan config:clear

CACHE_DRIVER=file

I deleted files bootsprap/cache/*, storage/framework/cache/*.

I tried everything!!!

I have this project on the github: https://github.com/iliyaZelenko/laravel-nuxt. Please help me, I want my project to be used by other people.



via Chebli Mohamed

Laravel 5 WebPack JQuery - $ is not defined

I Have webpack.min.js:

mix.webpackConfig(webpack => {
    return {
        plugins: [
            new webpack.ProvidePlugin({
                $: 'jquery',
                jQuery: 'jquery',
                'window.jQuery': 'jquery',
                Popper: ['popper.js', 'default'],
            })
        ]
    };
});

mix.sass('resources/assets/styles/index.scss', 'public/css/app.css')
    .js('resources/assets/scripts/index.js', 'public/js/app.js')
    .copyDirectory('resources/assets/static', 'public/static')
    .version()
    .sourceMaps();

and package.json:

"devDependencies": {
    "jquery": "^3.3.1",
    "axios": "^0.18.0",
    "bootstrap": "^4.1.3",
    "bootstrap-datepicker": "^1.7.1",
    "browser-sync": "^2.24.6",
    "browser-sync-webpack-plugin": "^2.0.1",
    "chart.js": "^2.7.2",
    "cross-env": "^5.2.0",
    "datatables": "^1.10.18",
    "easy-pie-chart": "^2.1.7",
    "font-awesome": "4.7.0",
    "fullcalendar": "^3.9.0",
    "jquery-sparkline": "^2.4.0",
    "jvectormap": "^2.0.4",
    "laravel-mix": "^2.1.11",
    "load-google-maps-api": "^1.2.0",
    "lodash": "^4.17.10",
    "masonry-layout": "^4.2.2",
    "perfect-scrollbar": "^1.1.0",
    "popper.js": "^1.14.3",
    "skycons": "^1.0.0",
    "vue": "^2.5.16"
  }

and in my blade footer script:

@section('footer')
    <script type="text/javascript">
        if (typeof jQuery != 'undefined') { alert(jQuery.fn.jquery); }

        $(function() {
        $('#cc-number').validateCreditCard(function(result) {
            $('.log').html('Card type: ' + (result.card_type == null ? '-' : result.card_type.name)
                + '<br>Valid: ' + result.valid
                + '<br>Length valid: ' + result.length_valid
                + '<br>Luhn valid: ' + result.luhn_valid);
        });
        });
    </script>
@endsection

after i run npm run dev and load my page, i receive error:

Uncaught ReferenceError: $ is not defined

and my alert(jQuery.fn.jquery); is not triggered

how do i load jquery from npm so then i can use it at inline html code in blade?



via Chebli Mohamed

why my javascript is not working after @section('content')

In my laravel 5.6 application I have image upload and preview system with javascript, this is my file,

                            <form method="POST" action="http://localhost:8000/laravel-crud-image-gallery/create" accept-charset="UTF-8" enctype="multipart/form-data"><input name="_token" type="hidden" value="1LLYc0D1spmVSFMboLDjGM9MR4O5APVwng7giejx">
                                <div class="form-group row required">
                <label for="description" class="col-form-label col-md-3 col-lg-2">Description</label>
                <div class="col-md-8">
                    <input class="form-control" autofocus placeholder="Description" name="description" type="text" id="description">

                </div> 
            </div>

                        <div class="form-group row">
                <label for="image" class="col-form-label col-md-3">Image</label>
                <div class="col-md-5">
                    <img id="preview"
                         src="http://localhost:8000/images/noimage.png"
                         height="200px" width="200px"/>
                    <input class="form-control" style="display:none" name="image" type="file" id="image">
                    <br/>
                    <a href="javascript:changeProfile();">Add Image</a> |
                    <a style="color: red" href="javascript:removeImage()">Remove</a>
                    <input type="hidden" style="display: none" value="0" name="remove" id="remove">
                </div>
            </div>
<div class="form-group row">
                <div class="col-md-3 col-lg-2"></div>
                <div class="col-md-4">
                    <a href="" class="btn btn-danger">
                        Back</a>
                    <button type="submit" class="btn
                btn-primary">Save</button>
                </div>
            </div>
            </form>
        </div>
    </div>
    @endsection

javascripts

<script>
        function changeProfile() {
            $('#image').click();
        }
        $('#image').change(function () {
            var imgPath = $(this)[0].value;
            var ext = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
            if (ext == "gif" || ext == "png" || ext == "jpg" || ext == "jpeg")
                readURL(this);
            else
                alert("Please select image file (jpg, jpeg, png).")
        });
        function readURL(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.readAsDataURL(input.files[0]);
                reader.onload = function (e) {
                    $('#preview').attr('src', e.target.result);
                    $('#remove').val(0);
                }
            }
        }
        function removeImage() {
            $('#preview').attr('src', 'http://localhost:8000/images/noimage.png');
            $('#remove').val(1);
        }
    </script>

but after add @section('content') to my script my image upload preview is not working without @section('content') is is working. how can fix this problem?



via Chebli Mohamed

Laravel 5.5: how to stop redirect to previous page after login

I am using Laravel default authentication When user loges in I redirect him/her to /dashboard instead of /home

changing this line in RedirectIfAuthenticated

return redirect('/home);`

to

return redirect('/dashboard');

now the if user hits another url that requires authentication lets say /abc it will redirect user to login but as soon as he/she gets login it takes user to /abc instead of /dashboard (As per my requirement)I want it to always take user to /dashboard whenever he/she loges in irrespective of previous page he/she was trying to hit

Anybody got any idea which function is to be overwritten or anything...



via Chebli Mohamed

Laravel 5. how to achieve this?

$stocks = StocksUnderMedication::where('user_id', Auth::user()->id)->get();

The above code gets all the rows that are in "StocksUnderMedication" table.

$originals = Stock::where('user_id', Auth::user()->id)->get();

The above code gets all the rows that are in "Stock" table.

I'm trying to get all the rows in the Stock table whose "tag_no" equals "tag" in StockUnderMedication table.

That is Stock table has tag_no field and StockUnderMedication has tag field.

How can i achieve this?



via Chebli Mohamed

Illuminate \ Http \ Exceptions \ PostTooLargeException No message

I need solution for this problem ,I have found many solutions but not working yet.enter image description here



via Chebli Mohamed

Where to put global php in Laravel application

Sorry if this is a silly question or has been answered before, but I just need a quick bit of advice!

Where is the best place in a Laravel 5 application to apply global php settings and why?

For example, if I want to set

ini_set('max_input_vars','10000');

and other various code that will be set globally across the application, where is best practise put it?

Please can someone properly explain where and why?



via Chebli Mohamed

why image uploader is not working in laravel 5.6

I am working with laravel 5.6. in my application I have image uploader with preview using javascripts. this is My image upload preview,

<div class="form-group row">
                <label for="image" class="col-form-label col-md-3">Image</label>
                <div class="col-md-5">
                    <img id="preview"
                          src=""
                         height="200px" width="200px"/>
                    <input class="form-control" style="display:none" name="image" type="file" id="image">
                    <br/>
                    <a href="javascript:changeProfile();">Add Image</a> |
                    <a style="color: red" href="javascript:removeImage()">Remove</a>
                    <input type="hidden" style="display: none" value="0" name="remove" id="remove">
                </div>

and my javascript

<script>
        function changeProfile() {
            $('#image').click();
        }
        $('#image').change(function () {
            var imgPath = $(this)[0].value;
            var ext = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
            if (ext == "gif" || ext == "png" || ext == "jpg" || ext == "jpeg")
                readURL(this);
            else
                alert("Please select image file (jpg, jpeg, png).")
        });
        function readURL(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.readAsDataURL(input.files[0]);
                reader.onload = function (e) {
                    $('#preview').attr('src', e.target.result);
                    $('#remove').val(0);
                }
            }
        }
        function removeImage() {
            $('#preview').attr('src', '');
            $('#remove').val(1);
        }
    </script>

but when I click Add I image button images not selecting, Then how can fix this problem?



via Chebli Mohamed

Illuminate\Database\QueryException : could not find driver

I am using centos on vps. I have installed laravel and postgres. But i get these errors, Illuminate\Database\QueryException : could not find driver (SQL: select * from information_schema.tables where table_schema = public and table_name = migrations)

at /home/admin/web/servers1.dreamploy.com/public_html/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664 660| // If an exception occurs when attempting to run a query, we'll format the error 661| // message to include the bindings with SQL, which will make this exception a 662| // lot more helpful to the developer instead of just the database's errors. 663| catch (Exception $e) {

664| throw new QueryException( 665| $query, $this->prepareBindings($bindings), $e 666| ); 667| } 668|

Exception trace:

1 PDOException::("could not find driver") /home/admin/web/servers1.dreamploy.com/public_html/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:68



via Chebli Mohamed

docker-compose up -d wont start php-fpm

im windows user.

i try to run laravel project with:

> docker-compose up -d (based on documentation)

all container running well except php-fpm error message

standard_init_linux.go:190: exec user process caused "no such file or directory"

when i running in server it running smoothly.

Question

please guide me to setting in windows envirovment.?



via Chebli Mohamed

how to convert laravel form collective to normal html form

I am working with laravel project. and need convert following laravel form collective to normal collective,

 <div class="form-group row">
                {!! Form::label("image","Image",["class"=>"col-form-label col-md-3"]) !!} // need change this
                <div class="col-md-5">
                    <img id="preview"
                         src=""
                         height="200px" width="200px"/>
                    {!! Form::file("image",["class"=>"form-control","style"=>"display:none"]) !!} // need change this
                    <br/>
                    <a href="javascript:changeProfile();">Add Image</a> |
                    <a style="color: red" href="javascript:removeImage()">Remove</a>
                    <input type="hidden" style="display: none" value="0" name="remove" id="remove">
                </div>
            </div>

how can I do this?



via Chebli Mohamed

applying alternate row color CSS for laravel table

How can I apply alternate row color CSS in laravel table. i want to display alternate color for the table rows. I've kept gridview cssclass in the table. I want to apply .gridview tr.even td for the even row count i.e. the rows with multiple of 2.

My CSS file

.gridview {
    font-family: "arial";
    background-color: #FFFFFF;
    width: 100%;
    font-size: small;
}

    .gridview th {
        background: #0CA3D2;
        padding: 5px;
        font-size: small;
    }

    .gridview td {
        background: #B6E1EE;
        color: #333333;
        font: small "arial";
        padding: 4px;
    }

    .gridview tr.even td {
        background: #FFFFFF;
    }

Table code

<table id="showBooksIn" class="table table-bordered gridview">
            <thead>
                <tr>
                    <th>BOOK ID</th>
                    <th>BILLED DATE</th>                      
                </tr>
            </thead> 
            <tbody>
                @foreach($ordered_books as $data)
                 <tr>
                     <td>  </td>                         
                     <td>  </td>
                 </tr>
                @endforeach
          </tbody>          
        </table>



via Chebli Mohamed

telegram link preview shows login

I have a website implemented by Laravel 5

I don't have any problems with telegram link preview itself.

Some of my pages are behind authentication which means users need to login to access those pages.

The problem is, when I put one of those links on telegram, it shows the preview for the login page instead of the intended URL. It is completely understandable and expected but I don't know how to solve it.

My first guess was that telegram uses a bot to do this but apparently it does not. I also tried working with user agent but I realized that the user agent it uses for this job is the same as browsers.

Any other ideas?



via Chebli Mohamed

dimanche 29 juillet 2018

Laravel: retrive and paginate all post belonging to one specific category

Ok, so I saw similar questions asked but none of the answers helped, so forgive me if it seems like this is a duplicate.

I am following a course on Udemy(It's been over a week, the instructor hasn't answered my question, although they are active on the site, hence why I'm here), the codes I'm displaying below is how the instructor has taught us to write it.

THE ISSUE: We are creating a blog and that blog has many categories and many posts but each post belongs to only ONE category which can hold multiple posts. Here's a look at the model for them.

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

public function posts(){
    return $this->hasMany('App\Post');
}

POST MODEL

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

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

They each have their own controller also, we also have a frontend controller that displays all the categories and when you click read more it takes you to a single page that displays the most recent post within that category. This single page also has a pagination that supposed to display the previous post that belongs to that category. INSTEAD: it takes the user to the most recent post regardless of what category it belongs to and display all the previous post for all category. Below is the frontend controller

        public function index()
{
    return view('categories')
           ->with('categories',Category:orderBy('created_at', 'desc')->take(24)->get())
           ->with('tag', Tag::all())
           ->with('posttitle', Post::orderBy('created_at', 'desc')->first());
}

public function tag($id)
{
    $tag = Tag::find($id);

    return view('tag')->with('tag', $tag)
                        ->with('categories', $tag->tag)
                        ->with('categories', Category::all());
}

public function singlePage($slug)
{
    $post = Post::where('slug', $slug)->first();

    $next_id = Page::where('id', '>', $page->id)->min('id');
    $prev_id = Post::where('id', '<', $post->id)->max('id');

    return view('single')->with('post', $post)
                                 ->with('categories', Category::all())
                                 ->with('posttitle', Post::take(1)->get())
                                 ->with('next', Post::find($next_id))
                                 ->with('prev', Post::find($prev_id));                                     
}

Here's a look at the view for the index function

<div class="container">

<div class="container-fluid">
    <div class="row medium-padding120 bg-border-color">
        <div class="container">
            <div class="col-lg-12">
            <div class="offers">
                <div class="row">
                    <div class="col-lg-8 col-md-12 col-sm-12 col-xs-12">
                        <div class="heading">
                            <h4 class="h2 heading-title">Discover New Articles</h4>
                            <div class="heading-line">
                                <span class="short-line"></span>
                                <span class="long-line"></span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="case-item-wrap">
                        @foreach($categories as $category)
                        <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
                            <div class="case-item">
                                <div class="case-item__thumb">
                                    <img src="" alt=""style="width:300px; height:280px;">
                                </div>
                                <h6 class="case-item__title text-center"><a href="#">{!! $category->title !!}</a></h6>
                                <!--<i class="seoicon-clock"></i>
                                 <time class="published" datetime="2016-04-17 12:00:00">
                                    
                                 </time>-->
                                <h6 style="width:300px; height:85px;">{!! str_limit($category->summary, 85) !!} 
                                    <small> <a href="">Read More</a></small>
                                </h6>
                            </div>
                        </div>
                        @endforeach
                    </div>
                </div>

            <div class="padded-50"></div>
        </div>
        </div>
    </div>
</div>

and this is the single page view below

    <div class="content-wrapper"> <div class="container"> <div>
<main class="main">
  <div class="col-xs-10 col-xs-offset-1 col-sm-10 col-sm-offset-1 col-md-7 col-md-offset-1 col-lg-6 col-lg-offset-3 panel panel-reading">
      <article class="hentry post post-standard-details">
        <h2>{!! $post->posttitle !!}</h2>
        <div class="post__content">

          <div class="post-additional-info">
            <div class="post__author author vcard">
              By:
              <div class="post__author-name fn">
                <a href="#" class="post__author-link"></a>
              </div>
            </div>

            
            <span class="post__date">
              <time class="published" datetime="2016-03-20 12:00:00">
                <i class="seoicon-clock"></i> 
              </time>
            </span>
            
          </div>

          
          <div class="post__content-info">
            <p> {!! $post->content !!} </p>
          </div>
          

        </div>

        <div class="pagination-arrow">
        
           @if($prev)
            <a href="" class="btn-prev-wrap">
                <svg class="btn-prev">
                  <use xlink:href="#arrow-left"></use>
                </svg>
                <div class="btn-content">
                  <div class="btn-content-title">Previous Page</div>
                    <p class="btn-content-subtitle"></p>
                </div>
            </a>
          @endif 

      
         @if($next)
           <a href="" class="btn-next-wrap">
             <div class="btn-content">
               <div class="btn-content-title">Next Page</div>
                 <p class="btn-content-subtitle"></p>
              </div>
              <svg class="btn-next">
                <use xlink:href="#arrow-right"></use>
              </svg>
            </a>
              @endif
        </div>

      </article>
  </div>
</main>

HERE'S the post database

    public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id');
        $table->integer('category_id');
        $table->string('posttitle');
        $table->string('slug');
        $table->text('content');
        $table->softDeletes();
        $table->timestamps();
    });
}

IN CONCLUSION: Using this how would you filter it so that only the post that has the same category_id is displayed when the user clicks on that category?

Thank you As a bonus I did a short screen recording of the problem https://www.screencast.com/t/vVzRMSunH



via Chebli Mohamed

laravel-echo, broadcast/auth returns empty response with 200 status

I am using pusher for driver, I've been trying to get laravel chat working, I think I have everything set up correctly until the auth request is fired after Echo initialization,

this is the request my vue component sends and response is empty

Broadcast::channel('messages.{id}', function ($user, $id) { return (int) $user->id === (int) $id; }); this is what my broadcast route looks like. Does anyone have any idea what is the problem with my request ?

let me know if info provided is insufficient.

PS. I have already uncomment App\Providers\BroadcastServiceProvider::class, line in my app.php



via Chebli Mohamed

Send value to show Function from Form Laravel

I have a Form in Blade and I need search a user based on his username. I want to use the show() function in controller. my form Looks like this

{!! Form::open(array('route' => 'userlookup.search', 'id' => 'userSearch', 'class' => 'needs-validation')) !!}

                    <div class="input-group mb-3">
                        <div class="input-group-prepend">
                            {!! Form::select('searchBy', array('UIN' => 'UIN', 'pNumber' => 'Permit Number', 'tNumber' => 'Transaction Number'), 'UIN', ['class' => 'form-control']); !!}
                            {!! Form::text('searchInput', '', array('class' => 'form-control', 'id' => 'searchInput')) !!}
                        </div>                            
                    </div>

                    <div class="input-group">
                        
                    </div>

                

and I want to send the value from the input field to show function to search the user and redirect to view. I have looked at couple of answers but each one gives me answer using which does not work here.

Thank You.



via Chebli Mohamed

PayPal REST API using OmniPay gives "AUTHENTICATION_FAILURE" on Laravel

I'm trying to integrate PayPal REST API using OmniPay and OmniPay PayPal on Laravel 5.6.

My gateway() function:

public function gateway()
{
    // Create a gateway for the PayPal RestGateway
    $gateway = Omnipay::create('PayPal_Rest');

    // Initialise the gateway
    $gateway->initialize(array(
        'clientId' => config('services.paypal.clientid'),
        'secret' => config('services.paypal.secret'),
        'testMode' => config('services.paypal.testmode'), // Or false when you are ready for live transactions
    ));


    return $gateway;
}

Purchase function in the same model:

public function purchase(array $parameters)
{
    $response = $this->gateway()
        ->purchase($parameters)
        ->send();

    return $response;
}

Checkout function in controller:

public function checkout($order_id, Request $request)
{
    $order = Order::findOrFail(decrypt($order_id));

    $paypal = new PayPal;

    $response = $paypal->purchase([
        'amount' => $paypal->formatAmount($order->amount),
        'transactionId' => $order->id,
        'currency' => 'USD',
        'cancelUrl' => $paypal->getCancelUrl($order),
        'returnUrl' => $paypal->getReturnUrl($order),
    ]);

    if ($response->isRedirect()) {
        $response->redirect();
    }

    return redirect()->back()->with([
        'message' => $response->getMessage(),
    ]);
}

The clientId and Secret are set correctly (tried changing and reentering it multiple times and the testMode is set to true in .env file.

Each time I try to submit the request I get this error:

Authentication failed due to invalid authentication credentials or a missing Authorization header.

What could possibly be the problem here?

Thanks in advance!



via Chebli Mohamed

Laravel/Guzzle Issue

Hello guys i have an issue when trying to use guzzle in laravel and i have spent ages trying to google it and research what the problem could be. This is a very simple get request for WHM/Cpanel api

$client = new Client();
$res = $client->request('GET', 'https://delta.cloudns.io:2087/json-api/accountsummary…', [
'auth' => [ 'username','passowrd']
]);

Now i get a 200 status for the request but i am not getting any data back and in the network tab on firefox/chrome tools the page is showing as a error 500.

The code above i put into the index of my controller. I have tested the username and password and url in postman and it works correctly and i get back the data i expect.

Any help would greatly appreciated. Thanks

enter image description here enter image description here



via Chebli Mohamed

Pagination like (Items per page: 25|50|75|100) in laravel

How to display specified number of records on web page?

Like : Items per page: 25 | 50 | 75 |100 If I select 25 then 25 records should be displayed.. I want this in laravel 5.5.. can anyone help me?



via Chebli Mohamed

Store function not working in Laravel

Can someone please help me fix this issue? When i click submit it doesnt work! I think the problem lies in the action="" of the form. Is the route correct? If it is why it is not working?

These are my routes:

Route::middleware(['auth'])->group(function () {

    Route::get('/', 'HomeController@index')->name('home');
    Route::resource('stocks', 'StockController');    
    Route::get('/stocks/{stock_tag}/doctor','DoctorController@index')->name('stock.doctor');
    Route::get('/stocks/{stock_tag}/doctor/create','DoctorController@create')->name('stock.doctor.create'); 
    Route::post('/stocks/{stock_tag}/doctor/store','DoctorController@store')->name('stock.doctor.store');    
});

My store function in DoctorController

public function store(Request $request,$stock_tag)
{
    //
    $stock = Stock::find($stock_tag); 
    if(Auth::check()){
            $doctor = Doctor::create([
                'date_of_visit' => $request->input('date_of_visit'),
                'doc_name' => $request->input('doc_name'),
                'remarks' => $request->input('remarks'),
                'description' => $request->input('description'),                                 
                'tag' => $stock->tag_no
            ]);               

            if($doctor){
                 return redirect()->route('stocks.doctor.index', ['doctor'=> $doctor->tag])             
                ->with('success' , 'Visit created successfully');
            }                
    }        
    return back()->withInput()->with('errors', 'Error creating new Visit');
}

This is my view:

 <form method="post" action="" enctype="multipart/form-data">       
    

    <div class="form-inline">
        <label for="date">Date of Visit</label>
        <input type="date" name="date_of_visit" max="2030-12-31">                     
    </div> 

    <div class="form-inline">
      <label for="doc_name">Doctor Name: </label>
      <input type="text" name="doc_name">          
    </div>

    <div class="form-inline">
      <label for="remarks">Remarks </label>
      <input type="text" name="remarks">          
    </div>

    <div class="form-inline">
      <label for="description">Medication and Execution </label>
      <input type="text" name="description">          
    </div>       
  </form>

  <div class="form-group">
    <input type="submit" class="btn btn-primary"
        value="Submit"/>      
</div>
</div>



via Chebli Mohamed