Monday, May 21, 2018

Eloquent Sluggable Package - development

Eloquent Sluggable Package

Adding unique slugs to your eloquent models is made simple through the Eloquent Sluggable package by Colin Viebrock. The gist of using this package is making your Eloquent models “sluggable” through the ‘Sluggable’ trait provided by the package, which defines an abstract sluggable() method you use to configure your model-specific configuration. Learn how to add slugs to your Laravel models with ease using this package!

Visit Laravel News for the full post.

The post Eloquent Sluggable Package appeared first on Laravel News.



from Laravel Questions and Answers https://laravelquestions.com/news/eloquent-sluggable-package/
via Lzo Media

Sunday, May 20, 2018

Laravel 5.5 save filename to database as *.tmp - development

Laravel 5.5 save filename to database as *.tmp

I want to save my post with linked image/
My model:

class Performer extends Model
{
    protected $fillable = ['title','slug','logoimage','description','address','toplace','exp','workers','published','created_by','modified_by'];

    public function categories() {
        return $this->morphToMany('AppCategory', 'categoryable');
    }

    public function SetSlugAttribute($value)
  {
    $this->attributes['slug'] = Str::slug(mb_substr($this->title, 0, 40) . "-". CarbonCarbon::now()->format('dmyHi'), '-');
  }
}

My controller:

public function store(Request $request) {

       // dd($request);
        $performer = Performer::create($request->all());

        if ($request->input('categories')){
            $performer->categories()->attach($request->input('categories'));
        }

        if ($request->hasfile('logoimage')){
          $image = $request->file('logoimage');
          $filename = time().'.'.$image->getClientOriginalExtension();
          $location = public_path('images/uploads/logo/'.$filename);
          Image::make($image)->resize(100, 100)->save($location);
          // dd($filename); - return normal filename, 857857857.jpg as example
          $performer->logoimage= $filename;

        }


        return redirect()->route('admin.performer.index');
    }

View:

<input type="file" class="form-control" name="logoimage">

enctype=”multipart/form-data” is enabled in form.

Result:
Images saved to folder publicimagesuploadslogo normally, with *.jpg names
To database (logoimage column) saved as C:xampptmpphp915C.tmp.
WHY?
How to fix it?



from Laravel Questions and Answers https://laravelquestions.com/php/laravel-5-5-save-filename-to-database-as-tmp/
via Lzo Media

Add more column in existing table but it doesn’t [duplicate] - development

Add more column in existing table but it doesn’t [duplicate]

This question already has an answer here:

$ php artisan migrate

In Connection.php line 647:

  SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users' alre
  ady exists (SQL: create table `users` (`id` int unsigned not null auto_incr
  ement primary key, `name` varchar(191) not null, `email` varchar(191) not n
  ull, `password` varchar(191) not null, `remember_token` varchar(100) null,
  `created_at` timestamp null, `updated_at` timestamp null) default character
   set utf8mb4 collate utf8mb4_unicode_ci)


In Connection.php line 449:

  SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users' alre
  ady exists

I am trying to add more column into users table but I can’t. In terminal I write command php artisan migrate but Base table or view already exists: 1050 Table ‘users’ already exists. What can I do now?



from Laravel Questions and Answers https://laravelquestions.com/php/add-more-column-in-existing-table-but-it-doesnt-duplicate/
via Lzo Media

Laravel on Window 10 using Wamp gives and error - development

Laravel on Window 10 using Wamp gives and error

I installed Laravel(5.6) on windows 10 with Wamp(3.1.). When I run the index file in Public folder in laravel to check if it is correctly installed or not using browser url, I get the following error:

Parse error: syntax error, unexpected ‘?’ in
C:wamp64wwwlaravelvendorlaravelframeworksrcIlluminateFoundationhelpers.php
on line 242.

So how can I solve this?



from Laravel Questions and Answers https://laravelquestions.com/php/laravel-on-window-10-using-wamp-gives-and-error/
via Lzo Media

Laravel Eloquent with() method works with ‘where’ but doesn’t work with ‘Model::find’ - development

Laravel Eloquent with() method works with ‘where’ but doesn’t work with ‘Model::find’

I want to have relationship between 3 tables, using Laravel Eloquent with() method.
this is my code (relationships are set in models):

    $request_form = RequestForm::find(7)->with(['RequestFormsCheck' => function ($q) {
        $q->orderBy("created_at", "DESC")->with('RequestFormsCheckOptions');
    }])->get();

    dd($request_form);

but this code returns all request forms except returning only id = 7
this is output:

Collection {#895 ▼
  #items: array:4 [▼
    0 => RequestForm {#796 ▶}
    1 => RequestForm {#797 ▶}
    2 => RequestForm {#798 ▶}
    3 => RequestForm {#799 ▶}
  ]
}

when I replace ->get() with ->first() it returns just request form, but its id is 1 🙁

but this code works great:

        $request_form = RequestForm::where('id', 7)->with(['RequestFormsCheck' => function ($q) {
            $q->orderBy("created_at", "DESC")->with('RequestFormsCheckOptions');
        }])->first();

        dd($request_form->toArray());

and this is its output (this is what I expect to get):

array:12 [▼
  "id" => 7
  "name" => "Jack"
  "email" => "jack@gmail.com"
  "telephone" => null
  "description" => "..."
  "site" => "http://branch.local/"
  "item_id" => 10
  "lang" => "en"
  "read" => 1
  "created_at" => "2018-05-15 11:09:47"
  "updated_at" => "2018-05-20 05:24:41"
  "request_forms_check" => array:1 [▼
    0 => array:8 [▼
      "id" => 1
      "request_form_id" => 7
      "type" => 2
      "request_forms_check_options_id" => null
      "description" => "custom note"
      "created_at" => "2018-05-15 11:48:36"
      "updated_at" => "2018-05-15 11:48:36"
      "request_forms_check_options" => null
    ]
  ]
]

these are my migrations:

    Schema::create('request_forms', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name', 100)->nullable();
        $table->string('email', 100)->nullable();
        $table->string('telephone', 20)->nullable();
        $table->text('description')->nullable();
        $table->string('site', 100);
        $table->integer('item_id');
        $table->string('lang');
        $table->timestamps();
    });

and

    Schema::create('request_forms_check_options', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title', 500);
        $table->timestamps();
    });

and this

    Schema::create('request_forms_checks', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('request_form_id')->unsigned();
        $table->foreign('request_form_id')->references('id')->on('request_forms')->onDelete('cascade');
        $table->tinyInteger('type')->comment("1: option, 2:description");
        $table->integer('request_forms_check_options_id')->unsigned()->nullable();
        $table->foreign('request_forms_check_options_id')->references('id')->on('request_forms_check_options')->onDelete('cascade');
        $table->text('description')->nullable();
        $table->timestamps();
    });



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-eloquent-with-method-works-with-where-but-doesnt-work-with-modelfind/
via Lzo Media

Laravel- arranging records in ascending and descending order - development

Laravel- arranging records in ascending and descending order

I have a create method in my controller

public function create()
{
$image = PropertyUser::where('user_id', '=', Auth::user()->id)->get();
foreach($image as $property)
{
    $id = $property->property_id;
}
$image_main = Image::where('property_id', $id)->get();
return view('settings.photos', ['image_array' => $image_main]);
}

This is my photos.blade file

<form name="asc" action="" method="post" class="text-center">
    @csrf
    <input type="submit"  value="Ascending " class="settings-photos-header2 text-center"/>  |
</form><form name="dec" action="" method="post"  class="text-center">
    @csrf
    <input type="submit"  value= " Descending" class="settings-photos-header2 text-center"/>
</form>
<h2 class="settings-photos-header2 text-center">Photo Gallery</h2>
@foreach ($image_array as $images)
    <div class="image-warp"><img src=""
                                 style="width:100px;height:100px;"><br/><span style="color: #1b1e21"></span>
    </form>
    </div>
    @endforeach

Question- How can i make the asc button sort the images in ascending order and des in descending order, is there a way to connect it to my controller, or is there a way to sort them in ascending and descending order through any other means?



from Laravel Questions and Answers https://laravelquestions.com/php/laravel-arranging-records-in-ascending-and-descending-order/
via Lzo Media

Using Intervention package to compress images. My images are not being compressed, still the same size - development

Using Intervention package to compress images. My images are not being compressed, still the same size

I’m using this package http://image.intervention.io/getting_started/installation to compress my images that’s uploaded to my server. However the images are not being compressed.

  1. First I installed the Intervention package by putting this in my
    terminal:

    composer require intervention/image

  2. Then I added this at the top of my controller:

    use InterventionImageImageManagerStatic as Image;

  3. Then I added the encode to minify the image

    Image::make(request()->file(‘img’))->encode(‘jpg’, 1);

  4. It’s not minifying the image. It’s still the same size.

    <?php
    
    namespace AppHttpControllers;
    
    use InterventionImageImageManagerStatic as Image;
    use IlluminateSupportFacadesStorage;
    use IlluminateHttpRequest;
    
    class UploadsController extends Controller
    {
    
        public function store()
        {
    
            // Get image
            $img = request()->file('img');
    
            // Minify image
            Image::make($img)->encode('jpg', 1);
    
            // Store image in uploads folder
            Storage::disk('public')->put('uploads', $img);
    
        }
    
    }
    
    


from Laravel Questions and Answers https://laravelquestions.com/php/using-intervention-package-to-compress-images-my-images-are-not-being-compressed-still-the-same-size/
via Lzo Media

URL generation removes port - development

URL generation removes port

I was trying to send an email when I encountered this error. So what I did is I created an event and on it’s listeners I want to send an email that will validate it’s email address. Just to be sure that everything will be secure I tried using URL::signedRoute to create a URL wherein if the user would click on it, it will go to the address produced by URL::signedRoute. What I just notice is that on the url that it created, there was no port in it.

Heres my mailable class

<?php

namespace AppMail;

use AppUser;
use IlluminateBusQueueable;
use IlluminateMailMailable;
use IlluminateQueueSerializesModels;
use IlluminateContractsQueueShouldQueue;
use IlluminateSupportFacadesURL;

class AccountValidation extends Mailable
{
    use Queueable, SerializesModels;

    public $user,$link;

    public function __construct(User $user)
    {
        $this->user = $user;
        $this->link = URL::temporarySignedRoute(
            'activateaccount', now()->addHour(), ['email'=>$user->email,'answer'=>'1']
        );
    }

    public function build()
    {
        return $this->from('welly@wellington.com')->view('emails.accountvalidation');
    }
}

The address from web.php

Route::get('/activate/{email}/{answer}','MyController@activateaccount')->name('activateaccount')->middleware('signed');

Here’s the URL that it produced.

http://localhost/activate/ewan@yahoo.com/1?expires=1526801279&amp;signature=823cfaece0a5184db2ef7e79e3f4bc9e3b4cbf362b98884323b0fe2605886912

I want the URL to have port 8000 like http://localhost:8000. Thank you for helping and excuse my grammar.



from Laravel Questions and Answers https://laravelquestions.com/php/url-generation-removes-port/
via Lzo Media

count in laravel 5.3 - development

count in laravel 5.3

I want to count table users row in laravel 5.3.

Here is my code Controller:

public function admin(){
    $jumlah['data'] = DB::table('users')->get();
    return view('admin',$jumlah);
}

In view, I call this count with :



Then I run and I get the message:

Undefined variable: jumlah (View: C:xampphtdocsBiroUmumresourcesviewsdashboardadmin.blade.php)



from Laravel Questions and Answers https://laravelquestions.com/php/count-in-laravel-5-3/
via Lzo Media

Get many to many from polymorphic table ID - development

Get many to many from polymorphic table ID

Using Laravel 5.1, how can I get Dialogs from a M:M relationship with a Polymorphic table.

When I load tasks, it loads the appropriate npc. This relationship between tasks and npcs is a Polymorphic relation.

So I created another M:M table, dialog_npcseventsmorphable, that links the dialog_id to the npcs_events_morphable_id on npcs_events_morphable table, but it is not loading the dialogs.

$task = Task::findOrFail(1);

npcs_events_morphable:

 id | npc_id | morphable_id | morphable_type |     created_at      |     updated_at      |    published_at     
----+--------+--------------+----------------+---------------------+---------------------+---------------------
  1 |      1 |            1 | AppTask       | 2018-05-20 04:45:24 | 2018-05-20 04:45:24 | 2018-05-20 04:45:24
  2 |      2 |            1 | AppActivity   | 2018-05-20 04:45:24 | 2018-05-20 04:45:24 | 2018-05-20 04:45:24
  3 |      3 |            1 | AppBattle     | 2018-05-20 04:45:24 | 2018-05-20 04:45:24 | 2018-05-20 04:45:24

dialog_npcseventsmorphable:

 dialog_id | npcs_events_morphable_id (<-- id on 'npcs_events_morphable' table)
-----------+--------------------------
         1 |                        1
         2 |                        1
         3 |                        2
         4 |                        2
         5 |                        3
         6 |                        3
         7 |                        3
         8 |                        3
         9 |                        3

Task:

class Task extends BaseModel
{
    protected $with = ['npcs', ...];

    public function npcs()
    {
        return $this->morphToMany('AppNpc', 'morphable', 'npcs_events_morphable');
    }
}

Npc:

class Npc extends BaseModel
{
    public function tasks()
    {
        return $this->morphedByMany('AppTask', 'morphable', 'npcs_events_morphable');
    }
    ...
}

Dialog:

class Dialog extends BaseModel
{
    public function npcs()
    {
        return $this->belongsToMany(NpcsEventsMorphable::class, 'dialog_npcseventsmorphable');
    }
    ...
}

NpcsEventsMorphable:

class NpcsEventsMorphable extends BaseModel
{
    protected $table = 'npcs_events_morphable';

    protected $with = ['dialogs'];

    public function dialogs()
    {
        return $this->belongsToMany(Dialog::class, 'dialog_npcseventsmorphable');
    }
}

}



from Laravel Questions and Answers https://laravelquestions.com/php/get-many-to-many-from-polymorphic-table-id/
via Lzo Media

Convert row data into column data using Laravel - development

Convert row data into column data using Laravel

Hello I am facing a problem. I am trying at my best to solve this but can not. I am trying to do this I have three table which is illustrated below image. I want to Output like last table in the given image

And this is my laravel code——————

$academic_year=$request->academic_year;
        $class=$request->class_name;
        $medium=$request->medium;
        $section=$request->section_name;        
        $exam_name=$request->exam_name;

        $subject_list=DB::table('tbl_subject')                    
                    ->where('class_name', 'LIKE', "%$class%")                                       
                    ->get();     


$student_all_subject_mark_search_result=DB::table('tbl_student_subject_mark') 
            ->join('tbl_student_admission', 'tbl_student_subject_mark.student_registration_id', '=', 'tbl_student_admission.student_registration_id')
            ->select('tbl_student_subject_mark.*', 'tbl_student_admission.student_registration_id',  'tbl_student_admission.student_full_name_english', 'tbl_student_admission.class', 'tbl_student_admission.medium', 'tbl_student_admission.section', 'tbl_student_admission.roll_no',
            'max(if(subject_name = "Bangla 1st Paper" , total_obtained_mark, null)) A',
            'max(if(subject_name = "Bangla 2nd Paper" , total_obtained_mark, null)) B',
            'max(if(subject_name = "English 1st Paper" , total_obtained_mark, null)) C',
            'max(if(subject_name = "English 2nd Paper" , total_obtained_mark, null)) D',
            'max(if(subject_name = "Mathematics" , total_obtained_mark, null)) E',
            'max(if(subject_name = "Religion" , total_obtained_mark, null)) F')
            ->where('tbl_student_subject_mark.academic_year', $academic_year)
            ->where('tbl_student_admission.class', $class)
            ->where('tbl_student_admission.medium', $medium)
            ->where('tbl_student_admission.section', $section)                
            ->where('tbl_student_subject_mark.exam_title', $exam_name)
            ->where('tbl_student_admission.student_registration_id is not null')
            ->groupBy('tbl_student_subject_mark.student_registration_id')                
            ->get();

But It shows an error

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'max(if(subject_name 
= "Bangla 1st Paper" , total_obtained_mark, null)) A' in 'field list' (SQL: 
select `tbl_student_subject_mark`.*, 
`tbl_student_admission`.`student_registration_id`, ..................



from Laravel Questions and Answers https://laravelquestions.com/laravel/convert-row-data-into-column-data-using-laravel/
via Lzo Media

Saturday, May 19, 2018

Why Design layout does not work in laravel in auth:make command - development

Why Design layout does not work in laravel in auth:make command

I’m new to laravel and I’m using laravel 5.6 but the problem is when I run auth:make command it execute and display some login field and register field. My question is why design layout is not working after running auth:make command in laravel. I have uploaded image it shows only html content but design layout is not showing.

Image link



from Laravel Questions and Answers https://laravelquestions.com/php/why-design-layout-does-not-work-in-laravel-in-authmake-command/
via Lzo Media

how to change tymon jwt authentication to use member model instead of user model in laravel 5.6? - development

how to change tymon jwt authentication to use member model instead of user model in laravel 5.6?

In my project I have users and members tables and eloquent models.
I’m going to use jwt authentication in members table and I changed corresponding config files, but still it goes to User model.

Here is config/auth.php :

return [

/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/

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

/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session", "token"
|
*/

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'jwt',
        'provider' => 'members',
    ],
],

/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/

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

    'members' => [
        'driver' => 'eloquent',
        'model' => AppModelsMember::class
    ]

    // 'users' => [
    //     'driver' => 'database',
    //     'table' => 'users',
    // ],
],

/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/

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

And here is config/jwt.php:

return [

/*
|--------------------------------------------------------------------------
| JWT Authentication Secret
|--------------------------------------------------------------------------
|
| Don't forget to set this, as it will be used to sign your tokens.
| A helper command is provided for this: `php artisan jwt:generate`
|
*/

'secret' => env('JWT_SECRET', 'changeme'),

/*
|--------------------------------------------------------------------------
| JWT time to live
|--------------------------------------------------------------------------
|
| Specify the length of time (in minutes) that the token will be valid for.
| Defaults to 1 hour
|
*/

'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,

/*
|--------------------------------------------------------------------------
| JWT hashing algorithm
|--------------------------------------------------------------------------
|
| Specify the hashing algorithm that will be used to sign the token.
|
| See here: https://github.com/namshi/jose/tree/2.2.0/src/Namshi/JOSE/Signer
| for possible values
|
*/

'algo' => 'HS256',

/*
|--------------------------------------------------------------------------
| User Model namespace
|--------------------------------------------------------------------------
|
| Specify the full namespace to your User model.
| e.g. 'AcmeEntitiesUser'
|
*/

'user' => 'AppModelsMember',

/*
|--------------------------------------------------------------------------
| User identifier
|--------------------------------------------------------------------------
|
| Specify a unique property of the user that will be added as the 'sub'
| claim of the token payload.
|
*/

'identifier' => 'id',

/*
|--------------------------------------------------------------------------
| Required Claims
|--------------------------------------------------------------------------
|
| Specify the required claims that must exist in any token.
| A TokenInvalidException will be thrown if any of these claims are not
| present in the payload.
|
*/

'required_claims' => ['iss', 'iat', 'exp', 'nbf', 'sub', 'jti'],

/*
|--------------------------------------------------------------------------
| Blacklist Enabled
|--------------------------------------------------------------------------
|
| In order to invalidate tokens, you must have the blacklist enabled.
| If you do not want or need this functionality, then set this to false.
|
*/

'blacklist_enabled' => env('JWT_BLACKLIST_ENABLED', true),

/*
|--------------------------------------------------------------------------
| Providers
|--------------------------------------------------------------------------
|
| Specify the various providers used throughout the package.
|
*/

'providers' => [

    /*
    |--------------------------------------------------------------------------
    | User Provider
    |--------------------------------------------------------------------------
    |
    | Specify the provider that is used to find the user based
    | on the subject claim
    |
    */

    'user' => 'TymonJWTAuthProvidersUserEloquentUserAdapter',

    /*
    |--------------------------------------------------------------------------
    | JWT Provider
    |--------------------------------------------------------------------------
    |
    | Specify the provider that is used to create and decode the tokens.
    |
    */

    'jwt' => 'TymonJWTAuthProvidersJWTNamshiAdapter',

    /*
    |--------------------------------------------------------------------------
    | Authentication Provider
    |--------------------------------------------------------------------------
    |
    | Specify the provider that is used to authenticate users.
    |
    */

    'auth' => 'TymonJWTAuthProvidersAuthIlluminateAuthAdapter',

    /*
    |--------------------------------------------------------------------------
    | Storage Provider
    |--------------------------------------------------------------------------
    |
    | Specify the provider that is used to store tokens in the blacklist
    |
    */

    'storage' => 'TymonJWTAuthProvidersStorageIlluminateCacheAdapter',

],

];

When I try to use JWTAuth::attempt($credentials) it returns error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘mobile’ in
‘where clause’ (SQL: select * from users where mobile =
98123456789 limit 1)

How could I fix this?



from Laravel Questions and Answers https://laravelquestions.com/php/how-to-change-tymon-jwt-authentication-to-use-member-model-instead-of-user-model-in-laravel-5-6/
via Lzo Media

set laravel mail setting to log file - development

set laravel mail setting to log file

I just start to learning laravel and now I have a problem with mail settings.

I want to send reset password email to the log file of the project and for this I change the .env file settings from MAIL_DRIVER = smtp to MAIL_DRIVER = log

I also change the mail.php settings and reset my server because I use (php artisan serve) command.

still i receive following error

SQLSTATE[42S02]: Base table or view not found: 1146 Table ‘mytodo.password_resets’ doesn’t exist (SQL: delete from password_resets where email = Ali@gmail.com

I don’t know why it is search for table.

I also see the following question it has same problem but my problem doesn’t solve by their instruction.

Laravel Mail to Log

please help me is there anything else i should try.



from Laravel Questions and Answers https://laravelquestions.com/laravel/set-laravel-mail-setting-to-log-file/
via Lzo Media

How to use Laravel’s 5.6 native Auth functionality with MongoDB - development

How to use Laravel’s 5.6 native Auth functionality with MongoDB

I am using the first-time laravel, and want to use the laravel Auth for login and registration, MongoDB as backend. Using this command enables the laravel Auth

    php artisan make:auth

will it work ? can anyone help me, how to do it..



from Laravel Questions and Answers https://laravelquestions.com/laravel/how-to-use-laravels-5-6-native-auth-functionality-with-mongodb/
via Lzo Media

Link to a specific part of a page - development

Link to a specific part of a page

I have a div that has lots of posts which is created dynamically from the database. The div has input for comment facility as well. I have no problems in posting the comments and I do it using a POST method. Then I redirect to the page using return redirect('/'); method. But it links to the beginning to the page which doesn’t create a good impression on the user. The user might be in the middle of the page and when he/she comments he will go to the beginning of the page and will have to scroll down again. Luckily, I have the divs with class equal to the post_id. So, isn’t there any method to go to the post in which the user posted using that class?



from Laravel Questions and Answers https://laravelquestions.com/php/link-to-a-specific-part-of-a-page/
via Lzo Media

View not loading when called from a Controller in Laravel - development

View not loading when called from a Controller in Laravel

I created a controller using artisan in my Laravel application, here’s the code:

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

class NavigationController extends Controller {

    public function welcome() {
        return view("welcome");
    }

}

When I use a Closure or load the view directly, everything works fine. But, when I load view from inside a controller, it couldn’t find it. Here’s my web.php file’s code:

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

The error it shows:
InvalidArgumentException View [NavigationController@welcome] not found.



from Laravel Questions and Answers https://laravelquestions.com/php/view-not-loading-when-called-from-a-controller-in-laravel/
via Lzo Media

Laravel get input data from POST request in a rest api - development

Laravel get input data from POST request in a rest api

i’m trying to get input data which i post them from rest api as an json format, but in laravel i can’t get them on controller and that return empty array of request

my api route:

Route::group(['prefix' => 'v1', 'namespace' => 'Apiv1'], function () {
    $this->post('login', 'ApiController@login');
});

and ApiController:

<?php

namespace AppHttpControllersApiv1;

use AppHttpControllersController;
use IlluminateHttpRequest;
use IlluminateSupportFacadesValidator;

class ApiController extends Controller
{

    public function login(Request $request)
    {
        dd($request->all());
    }
}

output:

[]

ScreenShot

Laravel get input data from POST request in a rest api



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-get-input-data-from-post-request-in-a-rest-api/
via Lzo Media

How to get the time at which the current user logged in in Laravel? - development

How to get the time at which the current user logged in in Laravel?

I’m using Laravel Authentication. How can I get the time at which the current user logged in? I want to calculate the number of seconds that have passed since the current user logged in. If there is a way to achieve it without using Events, it would be great.



from Laravel Questions and Answers https://laravelquestions.com/php/how-to-get-the-time-at-which-the-current-user-logged-in-in-laravel/
via Lzo Media

Project Specific PHP Error Log in Laravel Valet - development

Project Specific PHP Error Log in Laravel Valet

I just wanted to log PHP errors inside laravel project folder using Valet.

For Example – in Apache2 we can add php error log path (in my case my project folder) in virtual host and every time we add error_log($var); that will log errors inside project folder.

is it possible to create PHP Error log in Valet like so ?



from Laravel Questions and Answers https://laravelquestions.com/php/project-specific-php-error-log-in-laravel-valet/
via Lzo Media

Calculate average from array with fmod() - development

Calculate average from array with fmod()

I have a ratings array in which there are list of ratings of particular product from where i want the result to be average rating.

What i want to achieve is if average rating is 4.2 or 4.3 or something in between 4 to 4.5 it should result as 4.5 and if average rating is like 4.6 or 4.7 or something it should result as 5 rating.

I have done below stuff which is resulting 4.5 still if average rating os 4.2 or 4.6.

$product_ratings = Array
                  (
                     [0] => stdClass Object
                     (
                        [id] => 93
                        [product_id] => 5
                        [rating] => 5
                        [user_id] => 154
                     )
                     [1] => stdClass Object
                     (
                        [id] => 93
                        [product_id] => 5
                        [rating] => 5
                        [user_id] => 154
                     )
                     [2] => stdClass Object
                     (
                        [id] => 93
                        [product_id] => 5
                        [rating] => 3.5
                        [user_id] => 154
                     )
                     [3] => stdClass Object
                     (
                        [id] => 93
                        [product_id] => 5
                        [rating] => 5
                        [user_id] => 154
                     )
                     [4] => stdClass Object
                     (
                        [id] => 93
                        [product_id] => 5
                        [rating] => 2.5
                        [user_id] => 154
                     )
                     [5] => stdClass Object
                     (
                        [id] => 93
                        [product_id] => 5
                        [rating] => 4.5
                        [user_id] => 154
                     )
                   )
                $r = 0;
                $rating_total="";
                foreach ($product_ratings as $row) {
                    $rating_total += $row->rating;
                    $r++;
                }
                $average_rating = "";     
                if($rating_total != "" || $rating_total != 0)
                {
                    $average_rating = $rating_total / $r;
                }
                else
                {
                    $average_rating = 0;
                }
                $avg_rating = $average_rating - fmod($average_rating, 0.5);
                echo $avg_rating



from Laravel Questions and Answers https://laravelquestions.com/php/calculate-average-from-array-with-fmod/
via Lzo Media

Friday, May 18, 2018

Laravel 5.6 and reflection not finding class - development

Laravel 5.6 and reflection not finding class

I’m building a package in Laravel 5.6, im very new to building packages so im cutting and copying and learning as I go. so far so good, except i have run into a little issue.

My main package class is in packages/vendor/packagename/src/packagename.php

In that file, it is using a foreach loop to loop over the classes which i have inserted into the config file, so for example, i have a controller in app/Http/Controllers/TestController

// $class in this case equals TestController
foreach ( $allclasses as $class ) {
    $classMethods = [];

    $reflection = new ReflectionClass( $class );
}

When I run the code, i keep getting the following error;

Class TestController does not exist

The original code that i am copying this part from is found here https://github.com/Bulforce/laravel-ext-direct/blob/master/src/Bulforce/ExtDirect/ExtDirect.php at line 133.

I am taking the above code and building it for Laravel 5.6.

My TestController does exist. Im not sure whats going on. Is it trying to look for the controller in the packages/vendor/packagename/src/ directory?

Im really stumpted … Any help would be greatly appreciated.



from Laravel Questions and Answers https://laravelquestions.com/php/laravel-5-6-and-reflection-not-finding-class/
via Lzo Media

Laravel Creating relationship while updating - development

Laravel Creating relationship while updating

I have a library management system with Student and Book model. The structure of the tables are

Students Table

id | roll_no | name | created_at | updated_at

Books Table

book_id | name | author | publication | student_id | created_at | updated_at

Here, boook_id is the primary key

The relation is as follows

In Book Model

public function student()
{
    return $this->belongsTo('AppStudent');
}

In Student Model

public function books()
{
    return $this->hasMany('AppBook');
}

Initially the student_id in books table is null. Whenever a book is to be issued, book number and student roll number is supplied and the student_id field in books table is updated with the id of the student to whom it is being issued.

In the controller, I have the following code

public function postIssue(Request $request)
{
    $this->validate($request, [ 
        'rollno' => 'required|min:7',
        'bookno' => 'required|numeric',
    ]);
    $roll = $request->input('rollno');
    $bookno = $request->input('bookno');

    $student = Student::where('roll_no','=',$roll);
    $book = Book::where('book_id','=',$bookno);
    $book->student_id = $student->id;
    $book->save();

    return view('book.issue')->with('msg','Book Issued');
}

When I run this codes, I get a error saying
"Undefined property: IlluminateDatabaseEloquentBuilder::$id"

What is going wrong?
Is there a better way of doing this?

I am using Laravel 5.6



from Laravel Questions and Answers https://laravelquestions.com/php/laravel-creating-relationship-while-updating/
via Lzo Media

unable to find index for $geoNear query while using Laravel and MongoDB using Moloquent - development

unable to find index for $geoNear query while using Laravel and MongoDB using Moloquent

I am using the Moloquent model with Laravel 5.6. here is my collection record given below:-

{
    "_id" : ObjectId("5afe619dbe0b8d0e5876b16b"),
    "name" : "Central Park",
    "categories" : [ 
        "4d4b7105d754a06376d81259", 
        "4bf58dd8d48988d116941735", 
        "4bf58dd8d48988d119941735", 
        "4d4b7105d754a06376d81259", 
        "4bf58dd8d48988d116941735", 
        "4bf58dd8d48988d119941735", 
        "4d4b7105d754a06374d81259", 
        "4bf58dd8d48988d16d941735"
    ],
    "loc" : {
        "type" : "Point",
        "coordinates" : [ 
            88.4166612820784, 
            22.5835157504658
        ]
    }
}

I am running this query from the Laravel controller.

$users = MongoTest::where('loc', 'near', [
                    '$geometry' => [
                        'type' => 'Point',
                        'coordinates' => [
                            $longitude,
                            $latitude,
                        ],
                    ],
                    '$maxDistance' => 10,
                ])->get();

print_r($users);

I am getting this error:-

error processing query: ns=tkit.testTree: GEONEAR  field=loc maxdist=10 isNearSphere=0
Sort: {}
Proj: {}
 planner returned error: unable to find index for $geoNear query

How can I solve this?



from Laravel Questions and Answers https://laravelquestions.com/php/unable-to-find-index-for-geonear-query-while-using-laravel-and-mongodb-using-moloquent/
via Lzo Media

after filtering a plucked laravel collection, the indexed array change to Associative array - development

after filtering a plucked laravel collection, the indexed array change to Associative array

I have a collection of model eloquent such as user model, i use the pluck method to get the only post_idfrom this collection, this method give me the indexed array of post_id, but when i use filter or unique method for this indexed array the result change to Associative array. i don’t want a assoc array in result. I want just the unique of post_id’s in the indexed array. laravel auto changing my result.

$this->posts->pluck('post_id')->unique('post_id')  

result is :{ "1": 1 , "2": 2 }.

Is this can a bug or I have a mistake in fetching data by methods?



from Laravel Questions and Answers https://laravelquestions.com/laravel/after-filtering-a-plucked-laravel-collection-the-indexed-array-change-to-associative-array/
via Lzo Media

How to implement OCR in website using Laravel - development

How to implement OCR in website using Laravel

I need to implement OCR searching on my website using Laravel. How can I implement this in Laravel? Is this can be done only by open source OCR?

Any suggestion is appreciable.

Thanks



from Laravel Questions and Answers https://laravelquestions.com/php/how-to-implement-ocr-in-website-using-laravel/
via Lzo Media

Check duplication while uploading to database - development

Check duplication while uploading to database

I need to find duplicated details in the existing table while uploading a Excel file that contains some details,i need to find that by phone number and customer name. I am using mattexcel to upload the data into database.

I don’t want to insert that details if it is in there but other details must insert into that table

Controller

public function importExcel(Request $request)
    {
        if ($request->hasFile('import_file')) {
            Excel::load($request->file('import_file')->getRealPath(), function ($reader) {
                foreach ($reader->toArray() as $key => $row) {
                    $data['customername'] = $row['customername'];
                    $data['chassis'] = $row['chassis'];
                    $data['model'] = $row['model'];
                    $data['branchcode'] = $row['branchcode'];
                    $data['delivery'] = $row['delivery'];
                    $data['customerid'] = $row['customerid'];
                    $data['phone'] = $row['phone'];
                    $data['invoicedate'] = $row['invoicedate'];
                    $data['dse'] = $row['dse'];
                    $data['branch'] = $row['branch'];
                    $data['finance'] = $row['finance'];
                    $data['dono'] = $row['dono'];
                    $data['invoice'] = $row['invoice'];
                    $data['zsm'] = $row['zsm'];
                    $data['sm'] = $row['sm'];
                    $data['agm'] = $row['agm'];
                    $data['dsecode'] = $row['dsecode'];
                    $data['address'] = $row['address'];
                    $data['email'] = $row['email'];
                    $data['color'] = $row['color'];
                    $data['extendedwarrenty'] = $row['extendedwarrenty'];
                    $data['autocaddownload'] = $row['autocaddownload'];
                    $data['numberplate'] = $row['numberplate'];
                    $data['mcpstatus'] = $row['mcpstatus'];
                    $data['plandt'] = $row['plandt'];
                    $data['planok'] = $row['planok'];
                    $data['fasttag'] = $row['fasttag'];
//                    $data['settilment_pdf_path'] = $row['settilment_pdf_path'];
                    $data['rcstatus'] = $row['rcstatus'];
                    $branch = Branch::where([['branch_code', $row['branchcode']], ['status', 0]])->first();
                    $registration_id = Registration::orderBy('registration_id', 'desc')->take(1)->get();

                    if (count($registration_id) > 0) {
                        $regid = $registration_id[0]->registration_id;
                        $regid = $regid + 1;

                    } else {
                        $regid = 1;
                    }

                    $register = new Registration();
                    $register->registration_id = $regid;
                    $register->customername = $row['customername'];
                    $register->chassis = $row['chassis'];
                    $register->model = $row['model'];
                    $register->branchcode = $row['branchcode'];
                    $register->delivery = $row['delivery'];
                    $register->customerid = $row['customerid'];
                    $register->phone = $row['phone'];
                    $register->invoicedate = $row['invoicedate'];
                    $register->dse = $row['dse'];
                    $register->branch = $row['branch'];
                    $register->finance = $row['finance'];
                    $register->dono = $row['dono'];
                    $register->invoice = $row['invoice'];
                    $register->zsm = $row['zsm'];
                    $register->sm = $row['sm'];
                    $register->agm = $row['agm'];
                    $register->dsecode = $row['dsecode'];
                    $register->address = $row['address'];
                    $register->email = $row['email'];
                    $register->color = $row['color'];
                    $register->extendedwarrenty = $row['extendedwarrenty'];
                    $register->autocaddownload = $row['autocaddownload'];
                    $register->numberplate = $row['numberplate'];
                    $register->mcpstatus = $row['mcpstatus'];
                    $register->plandt = $row['plandt'];
                    $register->planok = $row['planok'];
                    $register->fasttag = $row['fasttag'];
                    $register->rcstatus = $row['rcstatus'];
                    $register->dealership = $branch->dealership_id;
                    $register->zone = $branch->zone_id;
                    $register->dh = $branch->dh_id;
                    $register->status = '0';
                    $register->created_user_id = Session::get('created_id');
                    $register->save();
                    $regidn = Registration::orderBy('registration_id', 'desc')->get();
                    $regidd = $regidn[0]->registration_id;

                    $ssitrack = new Ssi_track();
                    $ssitrack->registration_id = $regid;
                    $ssitrack->ssi_track_id = $regid;
                    $ssitrack->save();
                    $ssitrackk = Ssi_track::orderBy('ssi_track_id', 'desc')->get();
                    $ssitrackk = $ssitrackk[0]->registration_id;


                }
            });

        }
        return back()->with('success', 'Your File Is Successfully Uploaded To Database!');
    }



from Laravel Questions and Answers https://laravelquestions.com/php/check-duplication-while-uploading-to-database/
via Lzo Media

Composer update is slow - development

Composer update is slow

enter image description here

Whenever I use composer update, some packages are installing they will be installed, but it’s slow.

I and when it comes to this package, it just wont download, when I check my resources monitor, vagrant download speed is only 8 to 10kbps.

I have tried disabling xdebug by going to /etc/php/7.2/.

I have tried adding –prefer-dist still same problem.

What would be the solution for this? Thank you!



from Laravel Questions and Answers https://laravelquestions.com/laravel/composer-update-is-slow/
via Lzo Media

Laravel Image ( Working on store image ) - development

Laravel Image ( Working on store image )

I am working on a laravel store image function. Fortunately it is working. But my problem is when I’m trying to upload atleast 20+ images. It only stores the first 20 images.

My question is, is there any settings that restricts my code to upload 20+ more files ?

Here is my code

public function storeImages($keycode, $projectsID){
    if(!empty($_FILES[$keycode]['name']) && isset($_FILES[$keycode]) && is_array($_FILES[$keycode]['name'])):
        for($i = 0; $i < count($_FILES[$keycode]['name']); $i++):
            $filename = preg_replace("/[^a-z0-9A-Z.]/","_",$_FILES[$keycode]['name'][$i]);
            move_uploaded_file($_FILES[$keycode]['tmp_name'][$i],"uploads/projects/".$filename); //stores original size
            try{
                if(trim($filename) != ""){
                    $img = Image::make("uploads/projects/".$filename); //opens the original sizes
                    $img->resize(200,200); // resize original
                    $img->save('uploads/projects/200x200_'.$filename); // save resize images
                    $new = array();
                    $new['id'] = AppHelperModelHelper::uuid();
                    $new['project_id'] = $projectsID;
                    $new['type'] = "BEFORE";
                    $new['img_name'] = $filename;
                    DB::table("projects_photos")->insert($new);
                }
            }catch(Exception $e){

            }
        endfor;
    endif;
}



from Laravel Questions and Answers https://laravelquestions.com/php/laravel-image-working-on-store-image/
via Lzo Media

Slack notification for Laravel as it should be. Easy, fast, simple and highly testable. - development

Slack notification for Laravel as it should be. Easy, fast, simple and highly testable.

Slack notification for Laravel as it should be. Easy, fast, simple and highly testable. submitted by /u/Salamandra5
[link] [comments]


from Laravel Questions and Answers https://laravelquestions.com/rlaravel/slack-notification-for-laravel-as-it-should-be-easy-fast-simple-and-highly-testable/
via Lzo Media

Loop image in controller - development

Loop image in controller

MY CODE IN CONTROLLER :

 public function image_item_name($inc) 
{
    if(isset($_POST['inc'])) {
        $inc = $_POST['inc'];
        $i = DB::select("SELECT file_name FROM tbl_image_item_name WHERE inc = '$inc';");

        foreach ($i as $a){ 

          echo '<img src="../../">';

        }
    }else {
        echo "Access Denied";
    }

The Problem :
I cannot to loop the image from database, please help me.



from Laravel Questions and Answers https://laravelquestions.com/laravel/loop-image-in-controller/
via Lzo Media

Thursday, May 17, 2018

Video not working validation Laravel - development

Video not working validation Laravel

This is my code for the image the validation works but for audio and video does not work..

 private function getFileRules(){
            return array('question_image' => 'mimes:jpeg,jpg,png|max:10000',
                         'question_audio' => 'max:30000',
                         'question_video' => 'present|file|mimetypes:video/mp4,video/ogg|max:10000');
        }

        private function isFileValid($request){
            $rules = self::getFileRules();
            $validator = Validator::make($request->all(), $rules);
            if($validator->fails()){
                return false;
            }else{
                return true;
            }
        }

Why it does not work since it is the same code.?!



from Laravel Questions and Answers https://laravelquestions.com/laravel/video-not-working-validation-laravel/
via Lzo Media

Convert SQL Inner Join Custom to Eloquent Laravel - development

Convert SQL Inner Join Custom to Eloquent Laravel

Can I convert my custom SQL syntax into Eloquent Laravel, this is my SQL syntax:

SELECT a.* FROM krs a INNER JOIN (
                SELECT kode_matakuliah, MAX(bobot) as bobot_max
                FROM krs
                WHERE nim = 133341043
                GROUP BY kode_matakuliah
            ) b ON a.bobot = b.bobot_max AND a.kode_matakuliah = b.kode_matakuliah 
WHERE nim = 133341043



from Laravel Questions and Answers https://laravelquestions.com/laravel/convert-sql-inner-join-custom-to-eloquent-laravel/
via Lzo Media

Laravel serve – can’t post - development

Laravel serve – can’t post

I’m trying to build an API and wamp is having issues with the OAuth so I am using Laravel Serve. I am using Laravel 5.3 Passport, each time I POST, the response is blank and doesn’t respond the correct headers (Access-Control-Allow-Origin). It’s also only taking 9MS to get the response (which should be much longer, close to 600MS with PUT). However, if I use PUT, it works correctly.

VUE:

Vue.http.headers.common['Accept'] = 'application/json';
Vue.http.headers.common['Authorization'] = 'Bearer ' + token;

this.$http.post('http://127.0.0.1:8000/api/post/' + this.post.id + '/comment', formData)
            .then(response => {
                console.log(response);
            }, response => {
                // error
            });

Middleware:

protected $middleware = [
   BarryvdhCorsHandleCors::class,
];

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

Route:

Route::group(['middleware' => 'auth:api'], function() {
    // 
    Route::post('/post/{id}/comment, 'ApiPostCommentController@add');
});

Controller:

public function add(Request $request, $post_id)
{
   // 
   return response()->json(['status' => 'success'], 200);
}

Spending a lot of time on something that should just work – any ideas?

Thanks



from Laravel Questions and Answers https://laravelquestions.com/php/laravel-serve-cant-post/
via Lzo Media

Creating a test for password reset email – getting error (mailable not queued) when running test - development

Creating a test for password reset email – getting error (mailable not queued) when running test

I am using the auth that came with Laravel. I am testing the page where you put in your email and when you hit the submit button a password reset email will be sent to your email. The password reset email is sent when I do it manually. But I created this test to make sure the password reset email is sent but it's not working.

I am getting this error:

There was 1 failure: 1) The expected [IlluminateFoundationAuthResetPassword] mailable was not queued. Failed asserting that false is true.

I am using this code as a guide:

https://github.com/JeffreyWay/council/blob/master/tests/Feature/Auth/RegisterUserTest.php

<?php

namespace TestsControllersUnit; use TestsTestCase; use IlluminateSupportFacadesMail; use IlluminateAuthNotificationsResetPassword; use IlluminateFoundationTestingRefreshDatabase; class ResetPasswordEmailTest extends TestCase { use RefreshDatabase; public function setUp() { parent::setUp(); Mail::fake(); } /** @test */ public function does_send_password_reset_email() { $user = factory('AppUser')->create(); $this->post(route('password.email'), ['email' => $user->email]) Mail::assertQueued(ResetPassword::class); } } 

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



from Laravel Questions and Answers https://laravelquestions.com/rlaravel/creating-a-test-for-password-reset-email-getting-error-mailable-not-queued-when-running-test/
via Lzo Media

(1/1) FatalErrorException Call to a member function hasPermissionTo() on null in ClearanceMiddleware.php line 17 - development

(1/1) FatalErrorException Call to a member function hasPermissionTo() on null in ClearanceMiddleware.php line 17

https://scotch.io/tutorials/user-authorization-in-laravel-54-with-spatie-laravel-permission.

I have followed the above link for my reference to set roles and permissions to users.

I am getting the error.
(1/1) FatalErrorException
Call to a member function hasPermissionTo() on null

in ClearanceMiddleware.php line 17

My db tables are
This is my db table

Cleareance middleware code is:

namespace AppHttpMiddleware;

use Closure;
use IlluminateSupportFacadesAuth;

class ClearanceMiddleware {
/**
* Handle an incoming request.
*
* @param IlluminateHttpRequest $request
* @param Closure $next
* @return mixed
*/
public function handle($request, Closure $next) {
if (Auth::user()->hasPermissionTo(‘Administer roles & permissions’)) //If user has this //permission
{
return $next($request);
}

    if ($request->is('posts/create'))//If user is creating a post
     {
        if (!Auth::user()->hasPermissionTo('Create Post'))
     {
            abort('401');
        } 
     else {
            return $next($request);
        }
    }

    if ($request->is('posts/*/edit')) //If user is editing a post
     {
        if (!Auth::user()->hasPermissionTo('Edit Post')) {
            abort('401');
        } else {
            return $next($request);
        }
    }

    if ($request->isMethod('Delete')) //If user is deleting a post
     {
        if (!Auth::user()->hasPermissionTo('Delete Post')) {
            abort('401');
        } 
     else 
     {
            return $next($request);
        }
    }

    return $next($request);
}

}

Please clear this.



from Laravel Questions and Answers https://laravelquestions.com/php/1-1-fatalerrorexception-call-to-a-member-function-haspermissionto-on-null-in-clearancemiddleware-php-line-17/
via Lzo Media

Ajax page load with get parameter in Laravel 5.6 - development

Ajax page load with get parameter in Laravel 5.6

I am new laravel learner. I started a small project for my personal website. I am facing a problem. First i am giving my source code
Route:

Route::get('/p/{id}','mainController@portfolio');

Controller method:

public function portfolio($id)
{

    $project = PortItems::where('id',$id)->first();

    return view('kafi.p',['project' => $project]);
}

Link to Ajax File:

@foreach($projects as $project)

                    <figure class="item" data-groups='["all"]'>
                      <a class="ajax-page-load" href="">
                        <img src="" alt="">
                        <div>
                          <h5 class="name"></h5>
                          <small></small>
                          <i class="pe-7s-icon pe-7s-display2"></i>
                        </div>
                      </a>
                    </figure>

                    @endforeach

Blade File (p.blade.php):

<div id="ajax-page" class="ajax-page-content">
    <div class="ajax-page-wrapper">
        <div class="ajax-page-nav">
            <div class="nav-item ajax-page-prev-next">
                <a class="ajax-page-load" href="portfolio-5.html"><i class="pe-7s-icon pe-7s-angle-left"></i></a>
                <a class="ajax-page-load" href="#"><i class="pe-7s-icon pe-7s-angle-right"></i></a>
            </div>
            <div class="nav-item ajax-page-close-button">
                <a id="ajax-page-close-button" href="#"><i class="pe-7s-icon pe-7s-close"></i></a>
            </div>
        </div>

        <div class="ajax-page-title">
            <h1></h1>
        </div>

        <div class="row">
            <div class="col-sm-7 col-md-7 portfolio-block">
                <div class="owl-carousel portfolio-page-carousel">
                    <div class="item">
                        <img src="" alt="">
                    </div>
                    <div class="item">
                        <img src="" alt="">
                    </div>
                    <div class="item">
                        <img src="" alt="">
                    </div>
                </div>

                <script type="text/javascript">
                    function customAjaxScroll() {
                        var windowWidth = $(window).width();
                        if (windowWidth > 991) {
                            // Custom Ajax Page Scroll
                            $("#ajax-page").mCustomScrollbar({
                                scrollInertia: 8,
                                documentTouchScroll: false
                            });
                        } else {
                            $("#ajax-page").mCustomScrollbar('destroy');
                        }
                    }

                    jQuery(document).ready(function($){

                        // Ajax Loaded Page Scroll
                        customAjaxScroll();


                        $('.portfolio-page-carousel').owlCarousel({
                            smartSpeed:1200,
                            items: 1,
                            loop: true,
                            dots: true,
                            nav: true,
                            navText: false,
                            margin: 10
                        });

                    });

                    jQuery(window).on('resize', function() {
                        customAjaxScroll();
                    });
                </script>
            </div>

            <div class="col-sm-5 col-md-5 portfolio-block">
                <!-- project Description -->
                <div class="block-title">
                    <h3>Description</h3>
                </div>
                <ul class="project-general-info">
                    <li><p><i class="fa fa-user"></i> </p></li>
                    <li><p><i class="fa fa-globe"></i> <a href="" target="_blank"></a></p></li>
                    <li><p><i class="fa fa-calendar"></i> </p></li>
                </ul>

                <p class="text-justify"></p>
                <!-- /project Description -->

                <!-- Technology -->
                <div class="tags-block">
                    <div class="block-title">
                        <h3>Technology</h3>
                    </div>
                    <ul class="tags">
                        @foreach (explode(', ', $project->usedCodes) as $usedCodes)
                        <li><a></a></li>
                        @endforeach
                    </ul>
                </div>
                <!-- /Technology -->

                <!-- Share Buttons -->
                <div class="btn-group share-buttons">
                    <div class="block-title">
                        <h3>Share</h3>
                    </div>
                    <a href="#" target="_blank" class="btn"><i class="fa fa-facebook"></i> </a>
                    <a href="#" target="_blank" class="btn"><i class="fa fa-twitter"></i> </a>
                    <a href="#" target="_blank" class="btn"><i class="fa fa-dribbble"></i> </a>
                </div>
                <!-- /Share Buttons -->
            </div>
        </div>
    </div>
</div>

and here is my problem: http://ccnboalmari.com/test/#portfolio

I sent get parameter (id) from database correctly. but when I’m trying to open 2nd content or third, it shows only first id’s content. Sorry for my bad English.

thanks in advance. 🙂



from Laravel Questions and Answers https://laravelquestions.com/php/ajax-page-load-with-get-parameter-in-laravel-5-6/
via Lzo Media

RelationNotFoundException Call to undefined relationship [userStories] on model [AppUser] - development

RelationNotFoundException Call to undefined relationship [userStories] on model [AppUser]

I have created a relationship between User model and StoryModel. But it give me the Error

Call to undefined relationship [userStories] on model [AppUser].

May by i am missing something. Following is my code which i am using

Error:
enter image description here

User.php

<?php

namespace App;

use IlluminateNotificationsNotifiable;
use IlluminateFoundationAuthUser as Authenticatable;
use AppNotification;
use AppCheckIn;
use AppTravel;
use CarbonCarbon;
use AppNewInterest;
use AppUserStory;

class User extends Authenticatable
{
    use Notifiable;
    protected $table = "users";
    protected $primaryKey = 'id';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'firstname','lastname', 'user_id','email',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function userStories(){
        return $this->hasMany(UserStory::class, 'user_id', 'user_id');
    }
}

Controller Logic

$usersStories = User::with('userStories')
                            ->select('id','user_id','stories')
                            ->get();
 print_r($usersStories);
    exit;

Any initiative to help will be most appreciated. Thanks



from Laravel Questions and Answers https://laravelquestions.com/php/relationnotfoundexception-call-to-undefined-relationship-userstories-on-model-appuser/
via Lzo Media

How to call different methods of other classes to make a sheet and then merge sheet return from these methods to a excel file in Laravel? - development

How to call different methods of other classes to make a sheet and then merge sheet return from these methods to a excel file in Laravel?

I am using maatwebsite/Laravel-Excel to make excel sheet. What I need is I want to make 5 sheets in a single file I am able to make when using a common function to generate all sheets. But I want to make a sheet from the different function of some different class and then return this sheet to the calling function where we can merge different sheets to a single file.

The scenario is that:
1. We have a function where we will make a single file with 5 sheets.

    Excel::create($fileName, function ($excel) use ($productArray){
    //some code
    $excel->sheet($sheet_name, function ($sheet) use ($productArray){

    if($sheet_name=='test'){
    $x  = new abcController;
    $y = $x->exportComment();//it should return a sheet so that it can 
    be 
    merged
    }

    });

    });

  1. For first sheet we call a method like

    $x  = new abcController;
    $y = $x->exportComment();
    
    
  2. This exportComment() function will do like

    Excel::create('comment', function ($excel) use ($productArray){
    //some code
    $excel->sheet('comment', function ($sheet) use ($productArray){
    
    //code for generating sheet data(like row and cols etc.)
    }
    
    });
    
    });
    
    

now this exportComment() function will create a sheet (its working fine).
But how to return that sheet to the calling function?

I am not able to get proper answer. If anyone I can explain more clearly?

Please help whether I am going right or wrong.



from Laravel Questions and Answers https://laravelquestions.com/php/how-to-call-different-methods-of-other-classes-to-make-a-sheet-and-then-merge-sheet-return-from-these-methods-to-a-excel-file-in-laravel/
via Lzo Media

Retrieve files from Vue in Laravel - development

Retrieve files from Vue in Laravel

I uploaded files from my frontend using Vue to Laravel backend.

Uploaded using this snippet below:

addPost() {
axios.post('api/submitPropertyPhoto?token=' + this.token, this.postFormData)
 .then(r => {
 console.log(r)
})
.catch(e => {
console.log(e)
 }
},
uploadFieldChange(e) {
  for(let key in e.target.files) {
  this.postFormData.append('images[]', e.target.files[key])
   }
 }

When I want to request the file using normal Laravel request file helper method it returns nothing but when I use dd($request->files) it returns the details below.

FileBag {#68
  #parameters: array:1 [
  "images" => array:1 [
  0 => array:1 [
    "name" => UploadedFile {#45
      -test: false
      -originalName: "error.JPG"
      -mimeType: "image/jpeg"
      -size: 21806
      -error: 0
      path: "C:xampptmp"
      filename: "php639F.tmp"
      basename: "php639F.tmp"
      pathname: "C:xampptmpphp639F.tmp"
      extension: "tmp"
      realPath: "C:xampptmpphp639F.tmp"
      aTime: 2018-05-17 04:26:29
      mTime: 2018-05-17 04:26:29
      cTime: 2018-05-17 04:26:29
      inode: 0
      size: 21806
      perms: 0100666
      owner: 0
      group: 0
      type: "file"
      writable: true
      readable: true
      executable: false
      file: true
      dir: false
      link: false
      linkTarget: "C:xampptmpphp639F.tmp"
     }
    ]
  ]
 ]
}

What I want to achieve basically is to save the file in the disc and the file name in the database.



from Laravel Questions and Answers https://laravelquestions.com/laravel/retrieve-files-from-vue-in-laravel/
via Lzo Media

Laravel 5 download excel file (maatwebsite/excel) under storage/export through AJAX - development

Laravel 5 download excel file (maatwebsite/excel) under storage/export through AJAX

I want to download an excel file which stored into storage/export/ path. I used Maatwebsite excel provider for this in laravel 5.5.

My controller code is written below:

ob_end_clean();
ob_start();
Excel::create($excelName, function($excel) use($adminUserDataExcelSelected) {
$excel->sheet('Sheet 1', function($sheet) use($adminUserDataExcelSelected) {
$sheet->fromArray($adminUserDataExcelSelected);
});
})->store('xlsx');
ob_flush();
return response()->json(['path' => $path]);

My AJAX code is following;

$.ajax({
url: "/administrator/adminUser/exportselected/1/",
type:'POST',
data: {_token:_token, selected:selected, selectedField:selectedField},
success: function(data) { alert(data.path);
if($.isEmptyObject(data.error)){
}else{}
}
});

When I alert/ console.log the data.path, I received the below :

/var/www/html/stmd_OLD/storage/export/Admin-Users2018-05-17 04:46:47

My question is: How can instantly download the excel file now? Should I call another AJAX method here?



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-5-download-excel-file-maatwebsite-excel-under-storage-export-through-ajax/
via Lzo Media

Wednesday, May 16, 2018

Structure for Products table to store products details from various fields - development

Structure for Products table to store products details from various fields

I’m building an application which requires supporting various categories of fields of products (as in products in Fashion, Electronics, Automobile, Grocery etc.), so obviously, for products in every field (& even for their sub-categories), product properties would vary from category to category. Example: Products in Fashion field, are like Jeans, Shirts, etc. which have properties like size, color, type, material-type, etc., whereas Products in Electronics, can be like Mobile phones, Laptops, etc. which can have product properties like, processor, memory, storage, size, color, etc.

My Question is in regarding, how do I store such information in most generalized & efficient way possible?

What I’ve thought of a solution:

I’ve thought of creating three tables for maintaining this information.

  1. products table: This table will contain all products & their categories in nested set form such that each parent would act as a category and each leaf would act as a product. Along with this, this table would contain meta information about the product (like name, purchasing price, selling price, sku, etc. which would be common to any kind of product). Probable Table Structure of this table is as under:

    id(PK), client_fk(FK to clients), parent_id(for nested-sets), lft(for nested-sets), rgt(for nested-sets), depth(for nested-sets), name(meta), sku(meta), purchasing_price(meta), selling_price(meta), created_at, updated_at

  2. Other two tables will kinda work like EAV model structure. products_propstable: This table will store all possible properties to any product (from any category) like size, color, processor, memory, storage, etc. with their meta details like description, input-type-details, etc. Table Structure for this table can be

    id(PK), name, label, description, input_type, input_details, created_at, updated_at

  3. products_props_data table: This table will contain values for all the properties that product have. Table Structure for this table can be:

    id(PK), product_prop_fk(FK to products_props), product_fk(FK to products), value, created_at, updated_at

Reads on this information would be much more than inserts, updates or deletes.

Questions:

  1. Am I following the correct way?
  2. Is it efficient?
  3. Is there another way around?
  4. Advises/suggestions to achieve what I am trying to.


from Laravel Questions and Answers https://laravelquestions.com/php/structure-for-products-table-to-store-products-details-from-various-fields/
via Lzo Media

Variable in all controller and view fullcalendar laravel 5.6 - development

Variable in all controller and view fullcalendar laravel 5.6

I use fullcalendar in my web site in laravel 5.6 and it working 🙂 but when i change view i have this problem :

Undefined variable: calendar_details

In my view layout.app i have this :

{!! $calendar_details->script() !!}

Can i define this var in all controller and view to avoid all problem ?

This is my EventsController.php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use IlluminateSupportFacadesRedirect;
use AppHttpControllersController;
use Auth;
use Validator;
use AppEvents;

use Calendar;

class EventsController extends Controller
{
    public function index(){
        $events = Events::get();
        $event_list = [];
        foreach ($events as $key => $event){
            $event_list[] = Calendar::event(
                $event->event_name,
                true,
                new DateTime($event->start_date),
                new DateTime($event->end_date)
            );
        }
        $calendar_details = Calendar::addEvents($event_list);

        return view('events', compact('calendar_details'));
    }

    public function addEvent(Request $request){
        $validator = Validator::make($request->all(), [
            'event_name' => 'required',
            'start_date' => 'required',
            'end_date' => 'required',
        ]);

        if ($validator->fails()){
            Session::flash('warning', 'Veuillez entrer des informations valide');
            return Redirect::to('/events')->withInput()->withErrors('warning');
        }

        $event = new Events;
        $event->event_name = $request['event_name'];
        $event->start_date = $request['start_date'];
        $event->end_date = $request['end_date'];
        $event->save();

        Session::flash('success', 'Evènement ajouté avec succès');
        return Redirect::to('/events');

    }

}

and this is my Events.php :

<?php

namespace App;

use IlluminateDatabaseEloquentModel;

class Events extends Model
{
    protected $fillable = [
        'event_name', 'start_date', 'end_date'
    ];
}



from Laravel Questions and Answers https://laravelquestions.com/laravel/variable-in-all-controller-and-view-fullcalendar-laravel-5-6/
via Lzo Media

Laravel foreach ajax get HTTP 500 - development

Laravel foreach ajax get HTTP 500

This is my ajax

    $('#absensi').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget);
    var data_kelas = button.data('pkelas');
    var id = button.data('pid');
    var modal = $(this);
    //console.log(id);
    document.getElementById("vkelas").innerHTML = data_kelas;
    $.ajax({
      type : 'get',
      url : '',
      data : {'id': id},
      success:function(data){
        console.log(data); //check 
        $('#siswa').html(data);
      }
    });
  });

This is My Controller

      $output="";
      $admin = Auth::user()->sekolah_id;
      $murids= Student::where('sekolah_id', $admin)
      ->where('ruang_id', $request->id)
      ->get();
      if ($murids)
      {
        $i=1;
        foreach ($murids as $murid)
        {
          $stu .= '<tr><td>'.$i++.'</td>
                  <td>'.$murid->name.'</td>
                  </tr>';
        }
        return Response($stu); //show on html
      }

and I got error like this:

GET http://127.0.0.1:8000/detailclass?id=1 500 (Internal Server Error)

Can you help me?



from Laravel Questions and Answers https://laravelquestions.com/php/laravel-foreach-ajax-get-http-500/
via Lzo Media

Laravel relationship across multiple tables fails - development

Laravel relationship across multiple tables fails

I have the following tabels

table check

 id
 name ...

table setting type

id
name
level //references id on table check

tabel settings

type, //references type on table setting type
name
value

So basically i would like to return all checks with settings

So i have in my models

1.Check model // references table check

    public function settingsval(){
       return $this->hasMany('AppAppSettingTypes','name','name.setting');
   }

On my AppSettingTypes // references table setting type

    public function settings(){
       return $this->hasMany('AppAppSetting','id','type');
   }

SO on my controller am simply doing

CheckModel::with('settingsval')

But everytime the settings array is empty even though there is data

What could be wrong?



from Laravel Questions and Answers https://laravelquestions.com/php/laravel-relationship-across-multiple-tables-fails/
via Lzo Media

How to do auth without database in Laravel 5.6 - development

How to do auth without database in Laravel 5.6

I have to make default login in Laravel with: php artisan make:auth and I want to add 1 more authentication with API. In this auth API I don’t need database for login.

Is there any solution for this case?

I want to make custom provider and guard it but I am stuck at AlumniAuthProvider.php on AppAuth:

<?php

namespace AppAuth;

use IlluminateContractsAuthUser as UserContract;
use IlluminateContractsAuthAuthenticatable;
use IlluminateContractsAuthUserProvider;
use AppAuthUser;

class AlumniAuthProvider implements UserProvider {

    public function alumni()
    {           
    }

    public function retrieveById($identifier)
    {
    }

    public function retrieveByToken($identifier, $token)
    {
    }

    public function updateRememberToken(Authenticatable $user, $token)
    {
    }

    public function retrieveByCredentials(array $credentials)
    {
    }

    public function validateCredentials(Authenticatable $user, array $credentials)
    {       
    }
}

and Alumni.php on AppAuth:

<?php

namespace AppAuth;

use IlluminateContractsAuthAuthenticatable;
use IlluminateHttpRequest;

class Alumni implements Authenticatable
{
    public function getAuthIdentifierName()
    {
    }
    /**
     * Get the unique identifier for the user.
     *
     * @return mixed
     */
    public function getAuthIdentifier()
    {
    }

    /**
     * Get the password for the user.
     *
     * @return string
     */
    public function getAuthPassword()
    {        
    }

    /**
     * Get the token value for the "remember me" session.
     *
     * @return string
     */
    public function getRememberToken()
    {
    }

    /**
     * Set the token value for the "remember me" session.
     *
     * @param  string  $value
     * @return void
     */
    public function setRememberToken($value)
    {
    }

    /**
     * Get the column name for the "remember me" token.
     *
     * @return string
     */
    public function getRememberTokenName()
    {
    }
}

How could I make this custom API login?

In my opinion this code, which I made, is for second auth, or am I wrong? Maybe is there any other way to solve this problem?



from Laravel Questions and Answers https://laravelquestions.com/php/how-to-do-auth-without-database-in-laravel-5-6/
via Lzo Media

How to insert AM and PM in Mysql Database ? Thanks in advance - development

How to insert AM and PM in Mysql Database ? Thanks in advance

Thank You all for your precious time, I have seen lot of solution in internet for this problem, But cant get the apt solution for me

This is my value, I am going to insert in my
DB

[phoneinterview] => 2018-05-16 10:28 PM

In My databse I have field like this

phoneinterview timestamp

But Its Inserting Like this  -> 2018-05-16 10:28:00     
Actually I want to insert like this -> 2018-05-16 10:28 PM



from Laravel Questions and Answers https://laravelquestions.com/php/how-to-insert-am-and-pm-in-mysql-database-thanks-in-advance/
via Lzo Media

Ignore unique validation while update data - development

Ignore unique validation while update data

In my products table product_name is unique so while updating the data if i don’t update the product name it can’t let me update my product information and showing

product name has already been taken

My question is how to ignore unique name while while updating same product. Here is the code i have used for updating.

public function update(Request $request, $id)
  {
     $product = Product::find($id);     
     $this->validate($request, [ 
         'product_name'=> 'unique:products,product_name,'.$product->id ,          
     ]);  
     $product->product_name = Input::get('product_name'); 
     $product->product_unit_price = Input::get('product_unit_price');
     $product->save();         
     return Redirect::to('products');
  }



from Laravel Questions and Answers https://laravelquestions.com/php/ignore-unique-validation-while-update-data/
via Lzo Media

QueryException SQLSTATE[HY000] [2002] Connection refused [duplicate] - development

QueryException SQLSTATE[HY000] [2002] Connection refused [duplicate]

This question already has an answer here:

Not able to connect to database using laravel

PHP version: 7.1.10 MAC OSX

Error:

Whoops, looks like something went wrong.
(2/2) QueryException
SQLSTATE[HY000] [2002] Connection refused (SQL: SELECT * FROM project_categories WHERE status='A')

in Connection.php (line 647)
at Connection->runQueryCallback(object(Expression), array(), object(Closure))
in Connection.php (line 607)
at Connection->run(object(Expression), array(), object(Closure))
in Connection.php (line 326)
at Connection->select(object(Expression))
in DatabaseManager.php (line 324)`

ENV SETTINGS

APP_NAME=Somesite
APP_ENV=local
APP_KEY=base64:hFfau6WVxgBJ7GCmvnOK+GZd9/MuIy03zAqNCO8VTO8=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=somesite
DB_USERNAME=root
DB_PASSWORD=

Database.php configurations:

        mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'mahijaa'),
            'username' => env('DB_USERNAME', 'root'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],

Followed this thread: https://github.com/laravel/framework/issues/19522 to find solution but no use. What am i doing wrong, is it the problem with my code or environment. The same code works absolutely fine in windows machine. Recently migrated to mac OS and all went on toss



from Laravel Questions and Answers https://laravelquestions.com/php/queryexception-sqlstatehy000-2002-connection-refused-duplicate/
via Lzo Media

Empty model in Eloquent Global scope? - development

Empty model in Eloquent Global scope?

I am trying to determine if a user has the ability to update a model in a global scope, but I am using permission prefixes that I normally get through a relation.

The apply code is as follows:

public function apply(Builder $builder, Model $model)
{
    $user = getUser();

    if ($user === null || $user->cannot('update', $model)) {
        $builder->where('active', '=', 1);
    }
}

When I dd($model) the model is not actually instantiated so when I do my update permission check in my policy:

public function update(User $user, Item $item)
{
    return $user->hasAnyPermission(['edit-things', $this->prefix($item) . "-edit-item"]);
}

Where the prefix function looks like:

private function prefix(Item $item = null)
{
    if ($item !== null) {
        return $item->parentRelation->roles_permission_prefix;
    }
    $parentRelation= ParentRelation::findOrFail(request('parent_relation_id'));
    return $parentRelation->roles_permission_prefix;
}

It all fails due to their actaully not being a relationship. Any ideas?

Quick Edit: I am using the Spatie Permissions library if that is pertinent.



from Laravel Questions and Answers https://laravelquestions.com/laravel/empty-model-in-eloquent-global-scope/
via Lzo Media

Laravel routes are not found in 000webhost - development

Laravel routes are not found in 000webhost

I’m building a simple blog for my personal projects with Laravel 5.4.36. I have uploaded it to 000webhost. The problem is everytime I`m trying to sign up or sign in, it is saying,

The requested URL was not found on this server

Here is the URL that is shown during this error,

https://myprojectblog.000webhostapp.com/signUp

Here ‘signUp’ or ‘signIn’ are provided in the routes file which are given below,

Route::post('/signUp', [
    'uses'=>'UserController@postSignUp',
    'as'=>'signUp' 
]);

Route::post('/signIn', [
    'uses'=>'UserController@postSignIn',
    'as'=>'signIn' 
]);

The sign up form is given below,

<div class="signUp">

        <label>Sign Up</label></br>

        <form action="" method="POST" name="signUp" id="signUp">
            <label id="usernameLabelSignUp">Username</label></br>
            <input type="text" id="usernameSignUp" name="username" value=""></br>
            <label id="emailLabelSignUp">Email</label></br>
            <input type="text" id="emailSignUp" name="email" value=""></br>
            <label id="passwordLabelSignUp">Password</label></br>
            <input type="password" id="passwordSignUp" name="password"></br>            
            <input type="hidden" name="_token" value="">
            <input type="submit" id="signUpSubmit" value="signUp">
        </form></br>

    </div>

In the cpanel of 000webhost my file structure is,

/
  -Blog

      -All the Laravel project directories and files except public 

  -public_html

      -public
            -css
            -js
            -.htacess
            -index.php
            -favicon.ico
            -robots.txt
            -web.config

My index.php in /public_html/public got included these lines,

require __DIR__.'/../Blog/bootstrap/autoload.php';
$app = require_once __DIR__.'/../Blog/bootstrap/app.php';

The index page loads without any trouble, but while trying to sign in or up the error occurs.

Most importantly everything runs absolutely fine in my local machine, no trouble at all.

Some clue would mean great help. Thank you.



from Laravel Questions and Answers https://laravelquestions.com/php/laravel-routes-are-not-found-in-000webhost/
via Lzo Media