Laravel使用map()并返回视图+获取youtube视频ID

I'm trying to add the piece of code from How to get the id of youtube videos in laravel into my Controller.

Error:

Indirect modification of overloaded property App\Gallery::$link has no effect

GalleryController:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Gallery;

class GalleryController extends Controller
{
    //
    public function galleryAll()
    {

       $gallery = Gallery::orderBy('date', 'desc')
        ->get()
        ->map(function ($gallery) {
            $gallery->link = parse_str( parse_url( $gallery->link, PHP_URL_QUERY ), $gallery->link );
            return view('gallery', ['gallery' => $gallery]);
        });


    }
}

I'm unsure on how to save it to the $gallery-link. I'm planning on doing a @foreach in the View, and I want all the $gallery-link to be modified to only contain the youtube video code.

Update:

Controller

class GalleryController extends Controller
{
    //
    public function galleryAll()
    {

       return Gallery::orderBy('date', 'desc')
        ->get()
        ->map(function ($gallery) {
            return view('gallery', ['gallery' => $gallery]);
        });


    }
}

Page gives me:

[{},{},{},{},{},{},{},{},{},{},{},{},{}]

Using

$gallery = Gallery::orderBy('date', 'desc')

gives me blank page.

Returning the view should be the last part of your controller method.

map() basically takes the collection, loops through it and allows you to edit each iteration of the loop (each item in the collection) which in your case will be an instance of the Gallery model. So, what you're actually doing in you code is replacing each Gallery instance with an instance of Illuminate\View\View and then returning a collection of that.

As for the "Indirect modification of overloaded property" error you're getting have a look at: Indirect Modification of Overloaded Property Laravel MongoDB

I would suggest using an Accessor for this. In your Gallery model add the following:

public function getYoutubeIdAttribute()
{
    parse_str( parse_url( $this->link, PHP_URL_QUERY ), $query);

    return $query['v'];
}

Then your controller would just be something like:

public function galleryAll()
{
   $gallery =  Gallery::orderBy('date', 'desc')->get();

   return view('gallery', compact('gallery'));
}

And finally in your view you can simply access the youtube_id like:

@foreach($gallery as $g)

    {{ $g->youtube_link }}

@endforeach

you can't using: $gallery->link = parse_str($str, $gallery->link)

parse_str($str, $output);//output array
because $gallery->link is string
you see:http://php.net/manual/en/function.parse-str.php

</div>