RamjithAp

Software Developer at Saggezza Inc.

Experience

37,380

61 Best Reply Awards

  • Member Since 4 Months Ago
  • 1 Lesson Completed
  • 0 Favorites

9th February, 2018

RamjithAp left a reply on MySQL Cannot Add Foreign Key Contraint • 1 week ago

First migrate user table manually

php artisan migrate --path=/database/migrations/selected/

Then

php artisan migrate

RamjithAp left a reply on Error With Default Route Parameter • 1 week ago

You cannot have two dynamic routes in the same syntax for example

Route::get('tasks/{filter}', '[email protected]');
Route::get('tasks/{id}', '[email protected]');

You must change either one of them, since tasks/{id} is resource route I suggest to change the filter route bit like

Route::get('tasks/filter/{filter}', '[email protected]');
Route::resource('tasks', 'TasksController', ['except' => ['create', 'edit']])->middleware('WorkTextString');

8th February, 2018

RamjithAp left a reply on Insert In The Format Of 'dd/mm/yyyy' • 1 week ago

Try this

$data = Input::all();
$data['birthday'] = date('d/m/Y', strtotime($data['birthday']));
Model::insert($data);

RamjithAp left a reply on Error With Default Route Parameter • 1 week ago

If you want to add custom route to Resource collection just add before that route separately like this

Route::get('tasks/{filter}', '[email protected]');
Route::resource('tasks', 'TasksController', ['except' => ['create', 'edit']])->middleware('WorkTextString');

Check this https://laravel.com/docs/5.5/controllers#resource-controllers available resource routes by default. If any custom route can be added before the resource route.

RamjithAp left a reply on MySQL Cannot Add Foreign Key Contraint • 1 week ago

Make sure two things:

//If user User table migration has
$table->integer('id')->unsigned();
//Then change Profile table migration 
$table->integer('user_id')->unsigned();

And both the table should have same storage engine type like InnoDB.

15th January, 2018

RamjithAp left a reply on Error In Array In View File • 1 month ago

Try this in your view

@foreach($json->user->media->nodes as $node)
{{$node->name}}
@endforeach

11th January, 2018

RamjithAp left a reply on Laravel Csrf Session Timeout • 1 month ago

a work around for it, is to actually get the new token every certain time, otherwise you are defeating the purpose of the csrf token:

<html>
    <head>
        <meta name="csrf_token" content="{{ csrf_token() }}">
    </head>
    <body>
        <script type="text/javascript">
            var csrfToken = $('[name="csrf_token"]').attr('content');

            setInterval(refreshToken, 3600000); // 1 hour 

            function refreshToken(){
                $.get('refresh-csrf').done(function(data){
                    csrfToken = data; // the new token
                });
            }

            setInterval(refreshToken, 3600000); // 1 hour 

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

In laravel routes

Route::get('refresh-csrf', function(){
    return csrf_token();
});

3rd January, 2018

RamjithAp left a reply on I Need Help To Find Out A Solution • 1 month ago

Just change this

public function added_by_agent(){
        return $this->belongsTo('App\Models\Agent','added_by_id','id')->where('added_by','=',"agent");
 }

public function added_by_admin(){
        return $this->belongsTo('App\Models\Admin','added_by_id','id')->where('added_by','=',"admin");
 }

And then


$location_with_admin = Location::find($id)->with("added_by_admin")->get();

$location_with_agent = Location::find($id)->with("added_by_agent")->get();

RamjithAp left a reply on FastSMS With Laravel • 1 month ago

Place your sdk files in app directory for example ../app/fastSMS Now in your controller

include(app_path() . '\fastSMS\vendor\autoload.php');
$client = new FastSMS\Client('your token');
$data = [
    //set
    'destinationAddress' => 'Phone number or multiple numbers in array',
    //or
    'list' => 'Your contacts list',
    //or
    'group' => 'Your contacts group'

    'sourceAddress' => 'Your Source Address',
    'body' => 'Message Body', //Note: max 459 characters
    //optionals
    'scheduleDate' => time() + 7200, //now + 2h
    'validityPeriod' => 3600 * 6, //maximum 86400 = 24 hours
    'sourceTON' => 1, //The Type Of Number for the source address (1 for international, 5 for alphanumeric)
];
$result = $client->message->send($data);

RamjithAp left a reply on Messages On Login Page • 1 month ago

You notification table is empty either add some data or check before display it

<div class="message-widget">
@if($notices)
    @foreach ($notices as $notice)
        <h5>{{ $notice->data }} </h5>
    @endforeach 
@endif
</div>

RamjithAp left a reply on I Need Help To Find Out A Solution • 1 month ago

In your model

public function added_by_agent(){
        return $this->belongsTo('App\Models\Agent','added_by_id','id');
 }

or

public function added_by_admin(){
        return $this->belongsTo('App\Models\Admin','added_by_id','id');
 }

In your controller

if(Auth::User()->type=='admin'){
$location = Location::find($id)->with("added_by_admin")->get();
} else{
$location = Location::find($id)->with("added_by_agent")->get();
}
return $location;

29th December, 2017

RamjithAp left a reply on Trying To Get A Collection That Is Ordered By Sum Of A Relationship Column. • 1 month ago

Try this

$customers = Customer::where('name', 'like', '%' . $name . '%')
            ->whereHas('payments', function ($query) {
                $query->select(DB::raw('count(*) as payment_count'))
                ->where('payment', 'like', '%unpaid%')
                ->orWhere('payment', 'like', '%partial%');
            })
            ->orderBy('payments.payment_count','DESC')
            ->paginate(10);
        return new PendingOrderCollection($customers);

RamjithAp left a reply on Public APIs • 1 month ago

Why do you need to authendicate for public API's? And if you authenticate it becomes private.

RamjithAp left a reply on Unique View Counter • 1 month ago

Simply add a cookie in customer browser when he visits the first time, next time check for a cookie if not exist increase the count.

Alternatively, save user IP address and browser information in your database and check it to prevent repeated count.

RamjithAp left a reply on Trying To Get A Collection That Is Ordered By Sum Of A Relationship Column. • 1 month ago

Try this

$customers = Customer::where('name', 'like', '%' . $name . '%')
            ->whereHas('payments', function ($query) {
                $query->where('payment', 'like', '%unpaid%')
                ->orWhere('payment', 'like', '%partial%')
            })
            ->orderBy('payments.amount','DESC')
            ->paginate(10);
        return new PendingOrderCollection($customers);

28th December, 2017

RamjithAp left a reply on Fetch Data On Multiple Tables. • 1 month ago

@Snapey I just show him how to achieve with join queries, codes are not tested and accurate just copy pasted from above so.

RamjithAp left a reply on Is There A Way To Filter User Within A Distance Using Eloquent? • 1 month ago

First, get all the rows from locations table


$results = DB::table('CURRENT_LOCATIONS')->all();

foreach($locations as $location) {
   $json = file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?latlng=".$location->latitude.",".$location->longitude."&sensor=true");
   $city = $json["results"][0]["address_components"][4]["long_name"]; //it will return the city name brooklyn from below example api.
   $data[] = ["user_id"=>$location->user_id,"city"=>$city];
}

return $data; //now use array filter to get current user city and all the users from same city. 

API Example http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true

RamjithAp left a reply on How To Solve This Php Migrate Error • 1 month ago

Make sure these:

  1. Same data type ( INT , SINGED or UNSIGNED)
  2. Both table database engines (Innodb)
  3. Make sure Employee table ID column set as UNIQUE INDEX

RamjithAp left a reply on Fetch Data On Multiple Tables. • 1 month ago

If you decided to use join queries only, here is the solution.

public function getAllCarsByCity($id)
    {
      return $data = DB::table('vehicles')
      ->where([['cities.id',$id],['images.size','s'],['vehicles.vehicle_type_id',\App\VehicleType::Car],['status','approved'],['vehicles.isDeleted','false']])
      ->join('manufactures','manufactures.id' , '=' , 'vehicles.manufacture_id')
      ->join('brands','brands.id','=','manufactures.brand_id')
      ->join('models','models.id' , '=' , 'vehicles.model_id')
      ->join('model_versions','model_versions.id','=','vehicles.model_version_id')
      ->join('cities','cities.id' , '=' , 'vehicles.city_id')
      ->join('images','images.post_id' , '=' , 'vehicles.id')
      ->join('model_years','model_years.id','=','vehicles.model_year_id')
      ->join('engine_types','engine_types.id','=','vehicles.engine_type_id')
      ->join('transmissions','transmissions.id','=','vehicles.transmission_id')
      ->select('vehicles.*','engine_types.title as engine_type','transmissions.title as transmission','brands.title as manufacture','models.title as model','model_versions.title as model_version','cities.title as city','images.url as url','model_years.year as year')
      ->orderby('vehicles.featured','desc')
      ->paginate(35);

      $i = 0;
      $result = $data->toArray();
      foreach($result as $data){
          $images = '';
          $images = DB::table('images')->where('post_id',$data->id)->get();
          $images = $images->toArray();
          $result[$i] = array_merge($data,$images);
          $i++:
      }

      return $result;
    }

RamjithAp left a reply on How To Loop Data Into Table When The Data Column Is Less Than Column Header? • 1 month ago

Then just do

<html>
<head>
<style>
table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
}

tr:nth-child(even) {
    background-color: #dddddd;
}
</style>
</head>
<body>

<table>
<thead style="font-size: 12px">
    <tr>
         <td>Name</td>
        <td>Price</td>
        <td>Date</td>
    </tr>
    </thead>
    <tbody>
   @foreach($items  as $item)
        <tr>
        <td>{{ $item->name}}</td>
        <td>{{ $item->price}}</td>
        <td>{{ $item->date}}</td>
        </tr>
    @endforeach
    </tbody>
</table>

</body>
</html>

RamjithAp left a reply on Fetch Data On Multiple Tables. • 1 month ago

Use laravel relationships. First, in your User model do

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Get the comments for the blog post.
     */
    public function images()
    {
        return $this->hasMany('App\Images');
    }
}

And then in your image table model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Images extends Model
{
    /**
     * Get the post that owns the comment.
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

Now in your controller

$data = App\Post::user(1)->with('images');
return view('view_name',["data"=>$data]);

You view

@foreach($data->images as $image)
     <img src="{{ $image->url }}">
@endforeach 

RamjithAp left a reply on How To Loop Data Into Table When The Data Column Is Less Than Column Header? • 1 month ago

First in your controller take column names as well like below

public function showItems(){
$coulmns = DB::getSchemaBuilder()->getColumnListing('table_name');
$items = DB::table('table_name')->all();
return view("view_name", ["items"=>$items,"columns"=>$columns]);
}

Then your view

<html>
<head>
<style>
table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
}

tr:nth-child(even) {
    background-color: #dddddd;
}
</style>
</head>
<body>

<table>
<thead style="font-size: 12px">
    <tr>
   @foreach($columns as $column)
    <th>{{ $column }}</th>
   @endforeach
    </tr>
    </thead>
    <tbody>
   @foreach($items  as $items)
        <tr>
        <td>{{ $item->name}}</td>
        <td>{{ $item->etc}}</td>
        <td>{{ $item->etc}}</td>
        <td>{{ $item->etc}}</td>
        <td>{{ $item->etc}}</td>
        <td>{{ $item->price}}</td>
        <td>{{ $item->date}}</td>
        <td>{{ $item->created_at}}</td>
        </tr>
    @endforeach
    </tbody>
</table>

</body>
</html>

27th December, 2017

RamjithAp left a reply on Call To A Member Function ToArray() On Null • 1 month ago

Try

$user = \App\User::where([['name','Manny']])->first();
if($user){
$user = $user->toArray();
}
retrun $user;

RamjithAp left a reply on Expected Response Code 250 But Got Code "530", With Message "530 5.7.1 Authentication Required\r\n • 1 month ago

For using Gmail account as SMTP you must turn on less secure app settings in your Gmail account here https://myaccount.google.com/lesssecureapps

26th December, 2017

RamjithAp left a reply on Get Data • 1 month ago

$products = DB::table('products')
        ->where('product_name','LIKE','%'.$productname.'%')
        ->get();
foreach($products  as $product) {
        $images[] = $product->image;
}
return $images;

RamjithAp left a reply on Error Page • 1 month ago

Just use if conditions

if(Job::create($inputs)){
return redirect('indended_page')->with('session-message', 'Success');
} else {
return redirect('home')->with('session-message', 'Failed');
}

RamjithAp left a reply on Eloquent Return [#662 …25] Not Model Data • 1 month ago

@Snapey Just for the sake of showing some description data, I returned inside foreach.

RamjithAp left a reply on Eloquent Return [#662 …25] Not Model Data • 1 month ago

Try this

$posts= post::with('post_description')->all();
foreach($posts as $post){
return $post->post_description;
}

RamjithAp left a reply on Add New Column To Existing Table • 1 month ago

You must create a new migration for example if you have "articles" table and you want to add a new column " excerpt" you run this:

make new migration file, this creates a new file with up() and down() methods:

php artisan make:migration add_column_exceprt_to_articles --table="articles"

open up migration files in database/migrations (Laravel 5.3) edit migration files xxxx_xxx__xxx__xxx_add_column _excerpt_to_articles Edit up method for example

$table->string('excerpt'); // or $table->text('excerpt') if you want a text field instead varchar field

running

php artisan migrate

here you go, you have new column without losing data.

RamjithAp left a reply on How To Sort Out Products Corresponding To Thier Category Using Laravel 5.5 And Output Them To View • 1 month ago

Then you can simply use relationship query like this to bring all products corresponding to the category.

$result = Category::find($id)->with('products');
return $result;

RamjithAp left a reply on Eloquent Return [#662 …25] Not Model Data • 1 month ago

post_description is child array of post array and it can be multiple as Snapey comment. You have to do this way

$all = post::with('post_description');
return $all->post_description;

OR 

foreach($all->post_description as $desc){
return $desc;
}

If you are printing in your view then

@foreach($all->post_description as $desc)
<h2>{{ $desc->text }}</h2>
@endforeach

RamjithAp left a reply on Upload File Out Of The Project • 1 month ago

@vschavala Try this, For example, your project laravel project at ../xxx/laravel/public and another project at ../yyy/files now, go to your laravel file uploading controller and do:

public function uploadFile($request){

$file = Input::file('upload');
$file_name = $file->getClientOriginalName();
$file->move('/yyy/files/', $file_name);
return "Upload successful!";
}

RamjithAp left a reply on How To Avoid 500 Internal Server Error If Return Empty Data • 1 month ago

Just implement missing conditions in your controller

public function get_cust_data(Request $reques)
    {
        $arr = explode("-", $reques->st);
        $street = $arr[0];
        $from = $arr[1];
        $to = $arr[2];

        // Street ID
        $street_id = Street::select('id')
          ->where('name', $street)
          ->first()->id;
    

        // Object
        $street_data = StreetNumber::select('*')
          ->where('street_id',$street_id)
          ->where('from', $from)
          ->where('to', $to)
          ->get();
         
      if ($street_data ->count()) { // check street data exist for $from and $to
  
        $result = array();

        // Settlement ID
        $settlement_id = $street_data[0]->settlement_id;
        $result['settlement_id'] = $settlement_id;

        // Settlement Name
        $settl_data = Settlement::select('name')
          ->where('id',$settlement_id)
          ->get();

        // ElectoralUnit ID
        $electoral_unit_id = $street_data[0]->electoral_unit_id;
        $result['electoral_unit_id'] = $electoral_unit_id;

        // ElectoralUnit Name
        $el_unit_data = ElectoralUnit::select('name')
          ->where('id',$electoral_unit_id)
          ->get();

        // ElectoralUnitNumber
        $el_unit_number_data = ElectoralUnit::select('electoral_unit_number')
          ->where('id',$electoral_unit_id)
          ->get();

        $result['s_name'] = $settl_data[0]->name;
        $result['e_name'] = $el_unit_data[0]->name;
        $result['e_n_name'] = $el_unit_number_data[0]->electoral_unit_number;
        $result['street'] = $street;
        $result['str_id'] = $street_id;

        return response()->json(json_encode($result));

        } else {

        return response()->json(["msg"=>"Street data not exist!"]);  

        }
 
    }

RamjithAp left a reply on Clone A Live Site And Run On Localhost • 1 month ago

which means there must be some links broken, show us your console errors so we can help you.

RamjithAp left a reply on How To Sort Out Products Corresponding To Thier Category Using Laravel 5.5 And Output Them To View • 1 month ago

  1. Create products page
  2. List all the categories you have
  3. OnClick of category do Ajax and return products belongs to only that category and update the view.
  4. If not Ajax do redirect URL like products/category_name then show products relevant to that category.

Let me know if you stuck somewhere.

RamjithAp left a reply on User Tracking • 1 month ago

Create a Activity table in your database

id
user_id
job_id
activity
created_at

Then create model for it, and insert activity everytime controller do some specific job like below


public function addJob($request){
     
    $job_id = DB::table('job')->insertGetId($request->all()); //insert job & get ID
    DB::table('activity')->insert(['user_id'->Auth::user()->id,'job_id'=>$job_id,'activity'=>Auth::user()->name.' Added job']); // save activity
}

RamjithAp left a reply on How To Store Associative Array In Session Variable • 1 month ago

If you use 'push', when initially creating the array in the session, then the array will look like this only:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Catalyst
        )
)

Instead you should use 'put':

$request->session()->put('session_detail', ["id"=>1,"name"=>"Catalyst"]);

This will print

Array
(
            [id] => 1
            [name] => Catalyst
)

25th December, 2017

RamjithAp left a reply on Passing Default Input Value To Controller • 1 month ago

As you see your controller not getting the blog_id properly it just getting empty array , debug and fix that issue first.

23rd December, 2017

RamjithAp left a reply on Passing Default Input Value To Controller • 1 month ago

You supposed to fill blog_id value as well, change your controller like this.

public function store(Request $request, Blog $id)
{
    $this->validate($request, array(
        'name'  =>  'required|max:255',
        'email' =>  'required|email|max:255',
        'comment' =>'required|min:5|max:2000'
    ));

    $post = Blog::find($id);

    $comment = new Comment;
    $comment->blog_id = $id;
    $comment->name = $request->name;
    $comment->email = $request->email;
    $comment->comment = $request->comment;
    $comment->approved = true;
    $comment->blog()->associate($post);
    $comment->save();

    Session::flash('success', 'Comment was added');

    return back();
}

RamjithAp left a reply on Class App\Http\Controllers\CustomerController Does Not Exist, Exception: "ReflectionException", File: Container.php • 1 month ago

Run all this and try.

php artisan config:clear
php artisan route:clear
php artisan optimize
composer dump-autoload

RamjithAp left a reply on Base Table Or View Already Exists:1050 Table 'users' Already Exists In Connection.php Line 449 • 1 month ago

First, remove all your database tables completely. Then go to app>Providers>AppServiceProvider.php Add this line to the top,

use Illuminate\Support\Facades\Schema; 

In the boot() function add this line

Schema::defaultStringLength(191);

Then

php artisan cache:clear

php artisan config:cache

Now try migrate

php artisan migrate

let me know if there is any issues.

RamjithAp left a reply on How To Login Via Cookie To Laravel API • 1 month ago

Use Laravel builtin API package passport which will do all these things by default. Check https://laravel.com/docs/5.5/passport once you have passport installed, you can do below logic

getDataFromApi($url){
  if($_COOKIE['token']){
  //cuRL request to your API end point with token
  } else {
  //cuRl request to your login end point to get new token
  //then save the token in your local storage as cookie
  setcookie('token', $token, time() + (86400 * 30), "/"); 
  //cuRL request to your API end point with token
  }
return $results;
}

22nd December, 2017

RamjithAp left a reply on Uploading Project To Server • 1 month ago

Clear cache files

php artisan route:clear

RamjithAp left a reply on Laravel 5.5 - UpdateOrCreate() Does Not Add Any Record To Db • 1 month ago

Try firstOrNew()

$price= Price::firstOrNew(array('exchanges_id' => $tick['datetime']));
$price->ask= $tick['ask'];
$price->save();

RamjithAp left a reply on How To Take A Single Table Value Using Eloquent? • 1 month ago

Use pluck()

$default_type = \App\Ulbgt\TransferCriteria::where('id',$id)->pluck('default_type')->get(); 

RamjithAp left a reply on Getting Relation Of Relation In Blade • 1 month ago

Try this

$user = User::with('themes')->where([ ['slug', $slug], ['isauthor', 1], ['approved', 1] ])->firstOrFail();
$themes = $user->themes()->with('categories')->where('approved', 1)->limit(10)->get();
return view( 'userprofile',  [ 'user' => $user, 'themes' => $themes] );

And in your view

@foreach($themes as $theme)
  @foreach($theme->categories as $category)
       <h2>{{$category->name}}</h2>
  @endforeach
@endforeach

21st December, 2017

RamjithAp left a reply on How I Can Display Dynamically Username • 2 months ago

You have to do this in your view file

<h1>{{Auth->user()->id}}</h1>

RamjithAp left a reply on Hash • 2 months ago

Hashing produce different results each time you do. Because when you verify password it will check your database hash against user entered input. It will not COMPARE the hashes, it will use check/verify methods which will return true or false.

if (Hash::check('plain-text', $hashedPassword)) {
    // The passwords match...
}

Read this https://laravel.com/docs/5.5/hashing

RamjithAp left a reply on Search And Display Data In One Form • 2 months ago

It should work, if not you might be missing something else.

RamjithAp left a reply on Uploading Image To The Storage Folder • 2 months ago

You no need to create directory before save laravel creates automatically, try this

$image = Image::make($this->auditimage['Base64Image'])
                    ->resize(1000, 1000, function ($constraint) {
                    $constraint->aspectRatio();})
                    ->save( public_path("/images/".$userName."/".$auditTitle."/".$date."/").$this->filename);
                    $image->destroy();
Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.