samedi 28 avril 2018

Laravel/Angular 5/GoDaddy - All Image Paths Are Broke and Cannot Be Displayed

I'm working with a project that is using Laravel (api) and Angular 5 (front-end) on GoDaddy. In order to use Laravel safely on GoDaddy, I had to put all the Laravel files one directory back from public_html and all the Angular files in public_html. In order for this to work properly, I had to move the Laravel public folder to public_html and point to the Laravel file's via an absolute path. Everything is working so I know I'm headed in the right direction.

Laravel path - /home/website/laravel/

Public path - /home/website/public_html/

The only problem I'm having is trying to serve-up images for an image gallery. I store all the images in Laravel's storage directory and save the image path's in the db. When it's time to load all the images via Angular, I call the api and it returns all the image name's in a collection and Angular appends the path. Here's an example - https://website.com/storage/media/events/1/m_22721a76-8f0a-4ce2-97a5-e5ac169127a5.jpg.

Since my images are kept one directory back from public_html, they cannot be reached and are broke. My first thought is to save all the images in a directory in public_html, but I'm not sure if I can change Laravel's filesystems config to allow that. I also thought about trying to use .htaccess to detect a certain path and redirect, but I couldn't get it to work. I feel like using Laravel's filesystems is the way to go, but couldn't get it to work, here is what I came up with:

filesystems.php

'public' => [
    'driver' => 'production',
    'root' => storage_path('/home/website/public_html/storage/media/'),
    'url' => env('APP_URL').'/storage',
    'visibility' => 'public',
],

ImageGalleryController.php

if(App::environment('local'))
{
    Storage::disk('local')->put('events' . '/' . $id . '/t_' . $path, (string) $thumb->encode());
}
else if(App::environment('test')) 
{
    Storage::disk('test')->put('events' . '/' . $id . '/t_' . $path, (string) $thumb->encode());
}
else {
    Storage::disk('production')->put('events' . '/' . $id . '/t_' . $path, (string) $thumb->encode());
} 

With my current file setup, any ideas how I can display images from Laravel's storage directory?



via Chebli Mohamed

How do I know if my route is reached?

I'm working with Laravel 5 and I'm trying to call the destroy function inside my Controller

HTML

<div class="modal fade" id="deletePub" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true">
   <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h6 class="modal-title" id="modalPublicationTitle">Confirm Publication Delete</h6>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">    
                <form id="msform" action="" method="post">
                    
                        
                    <div class="row align-items-center">
                        <div class="col-lg-12" align="center">Really, do you want to delete this publication?</div>
                       <button type="button" class="btn btn-danger btn-sm" id="btn-confirmDeletePub">Yes, Delete </button> 
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

JS

$(document).ready(function() {
    $("#btn-confirmDeletePub").click(function(){

        $.ajaxSetup({
            headers: {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')  
            }
        });

        var publicationId = window.location.href.split("/")[4]

        console.log(publicationId);

        $.ajax({
            type: "POST",
            url: "/publications/" + publicationId,
            data: {_method: 'delete'},
            //contentType: "application/json; charset=utf-8",
            //dataType: "json",
        });
    });
});

web.php

Route::resource('publications','PublicationController');

PublicationController.php

/**
 * Remove the specified resource from storage.
 *
 * @param  int $id
 * @return \Illuminate\Http\Response
 */
public function destroy($id)
{
    $publication = Publication::find($id);
    dd($publication);
    $publication->users()->detach($publication->id);
    $publication->topics()->detach($publication->id);
    $publication->authors()->detach($publication->id);

    $publication->details()->delete();

    //$publication->delete();

    Redirect('/users')->with('success', 'Publication deleted correctly.');

}

the html code calls the btn-confirmDeletePub function of the JS file when I click on the Yes, delete button. The JS button captures the id of the publication to be deleted and will sent to the destroy($id) function of the PublicationController, but I don't have the certainty that the method is called. I tried to put a dd($ publication) to print on the Google Chrome's console, but nothing to do. The error I get is: POST http://localhost:8000/publications/4 500 (Internal Server Error).



via Chebli Mohamed

Laravel validate returns "error" instead of "errors"

Using laravel 5.6, I currently, I get a 422 JSON response like this when a validation error occurs using $request->validate($rules):

{
    "error": {
        "isbn": [
            "The isbn field is required."
        ],
        "price": [
            "The price field is required."
        ]
    }
}

Instead, I expect it to be:

{
    "errors": {
        "isbn": [
            "The isbn field is required."
        ],
        "price": [
            "The price field is required."
        ]
    }
}

I noticed that the defaults in the RegisterController do return the plural of error when the validator is called with return Validator::make($data, $rules)...

Why do I get the singular form with $request->validate($rules)?



via Chebli Mohamed

Laravel 5, sometimes loads very slow

I've been with Laravel 5 for a while, I've been doing tests and I have a problem that I do not know about because it occurs.

Sometimes, when I load a page, for example: www.myweb.com/admin Route::any('/admin', "IndexController@indexAdmin");the page loads in a few seconds. However, other times you are accessing this same page, it takes 20 seconds or more to load.

When the page takes time to load, if I click on the button to stop loading the page and I give it to reload page, the same thing happens.

However, if in case the page takes a long time to load, click on the url and press enter, as it would be normal, a few seconds.

When I say that the page is slow to load, I say that the DOM is slow to load, not the photos, videos, etc.

The css background always loads without any problem.

Does anyone know why?

I can not put code because I do not know what code should I put



via Chebli Mohamed

Condition in my view

i have a another problem in my view This condition @if dont work :

@if( ! empty($news))
    <div class="container">
        <div class="row justify-content-center">
            <h1 style="color:#fff;text-decoration:underline;margin-left:20px;">Any News !</h1>
        </div>
    </div>
@else
    <h1 style="color:#fff;text-decoration:underline;margin-left:20px;">Last News :</h1>
    <div class="col-md-8">
        <div class="row">
            @foreach($news as $new)
                <div class="card" style="width: 18rem; margin-left:30px;">
                    <img class="card-img-top img-responsive" style="height:160px;" src="img/.jpg" alt="Card-news-">
                    <div class="card-body">
                        <h5 class="card-title"></h5>
                        <p class="card-text">
                            @if(strlen($new['content'])>150)
                                ...
                            @else
                                
                            @endif
                        </p>
                        <a href="#" class="btn btn-primary">More.</a>
                        @if(@admin)
                            <a href="" class="btn btn-warning">Edit</a></td>
                            <form action="" method="post">
                                @csrf
                                <input name="_method" type="hidden" value="DELETE">
                                <button class="btn btn-danger" type="submit">Delete</button>
                            </form>
                        @endif
                    </div>
                </div>
            @endforeach
        </div>
    </div>
@endif

i would to show Any News ! when don't have news and Last News ! when i have news Can you help me ^^ ?



via Chebli Mohamed

How to get multiple result using Eloquent

I can get first result using this code

public function search(Request $request)
{
    $record = St::where('pn', $request->input)->first();
    $param = ['input' => $request->input, 'record' =>$record];
    return view('contacts.find', $param);

}

but, I changed like this

        $record = St::where('pn', $request->input)->get();

error show up

Method Illuminate\Database\Eloquent\Collection::getData does not exist

Could someone tell me why?

my version is 5.6



via Chebli Mohamed

How to keep previously inserted data if I send blank data while updating through UpdateOrCreate method of Laravel Eloquent?

I am new in Laravel. I am using the UpdateOrCreate method of Laravel and I am trying to update some fields of the form and other fields will be as like as earlier. Let, I have three fields in the form which are user_bio, user_image, user_cover_image. I want to update uer_bio only. I tried various way but I failed. I need to update will fields together! How can I solve this issue?

Here are my codes: profile.blade.php (front-end view):

<div class="card">
                <div class="card-header"> প্রোফাইল </div>
                <div class="card-body">
                    <form action="profile/store" method="post" enctype="multipart/form-data">
                    @csrf
                    
                    <div class="form-group">
                        <label for="user_bio">Bio:</label>
                        <input type="text" class="form-control" id="user_bio" name="user_bio">
                    </div>

                    <div class="form-group">
                        <label>Upload your profile picture:</label>
                        <input type="file" class="form-control" name="profilepicture" id="profilepicture">
                    </div>

                    <div class="form-group">
                        <label>Upload your cover photo:</label>
                        <input type="file" class="form-control" name="coverphoto" id="coverphoto">
                    </div>
                    

                    <button type="submit" class="btn btn-default" name="submit" value="submit">Submit</button>
                    </form>
                </div>
                
            </div>

ProfileController:

/** User Profile Picture (with URL) Storing Process Starts here **/
    $image = $request->file('profilepicture');
    $imagenewname= rand() .'.'. $image-> getClientOriginalExtension();
    $path = $request->file('profilepicture')->storeAs(
        'public/UserImages', $imagenewname
    );

    $imageName = "UserImages/".$imagenewname;
    /** User Profile Picture (with URL) Storing Process Ends here **/


    /** User Cover Photo (with path) Storing Process Starts here **/
    $coverphoto = $request->file('coverphoto');
    $coverphotoname= rand() .'.'. $coverphoto-> getClientOriginalExtension();
    $coverphotopath = $request->file('coverphoto')->storeAs(
        'public/CoverPhotos', $coverphotoname
    );

    $coverPhotoName = "CoverPhotos/".$coverphotoname;
    /** User Cover Photo (with path) Storing Process Ends here **/



    $check = Profile::updateOrCreate(['user_id' => $request->user_id], ['user_bio' => $request->user_bio, 'user_image' => $imageName, 'user_cover_image' => $coverPhotoName]);



via Chebli Mohamed