首页 > 解决方案 > Laravel - 当前登录用户的数据存储/获取

问题描述

我正在尝试在 laravel 中存储和获取当前登录用户的数据,但除了错误之外我什么也没得到

[

[Route: authlyrics.show] [URI: painel/authlyrics/{authlyric}] 缺少必需的参数。(查看:/var/www/html/allup_lyrics_cms/resources/views/admin/userlyrics/index.blade.php)

]

我的意思是我有两张桌子。一个是用户表,存储登录数据,另一个表是歌词表,存储用户将添加到站点的歌词。如何存储此经过身份验证的用户歌词并获取歌词以在索引页面中列出它们?而歌词和用户是通过 user_id 外键绑定的。我的代码在这里给出:

**

歌词列表 - admin > userlyrics > index.blade.php / edit.blade.php / create.blade.php / show.blade.php

**

@extends('adminlte::page')

@section('title', 'Minha Lista de Músicas')

@section('content_header')
<h1>Minha Lista de Músicas
<a href="{{ route('authlyrics.create') }}" class="btn btn-sm btn-success ml-3 text-uppercase">Adicionar nova
    música</a>
</h1>
@endsection

@section('content')

<div class="card">
<div class="card-body">
    <table class="table table-hover">
        <thead>
            <tr>
                <th width="50">ID</th>
                <th>Artista</th>
                <th>Título</th>
                <th>Extra Info</th>
                <th>URL da Música</th>
                <th width="200">Ações</th>
            </tr>
        </thead>

        <tbody>
            @foreach ($lyrics as $lyric)
            <tr>
                <td>{{ $lyric->id }}</td>
                <td>Nome do Artista</td>
                <td>{{ $lyric->title }}</td>
                <td>{{ $lyric->info }}</td>
                <td>{{ $lyric->video_url }}</td>
                <td>
                    <a href="{{ route('authlyrics.show', ['lyric' => $lyric->id]) }}" target="_blank"
                        class="btn btn-sm btn-success">Ver</a>

                    <a href="{{ route('authlyrics.edit', ['lyric' => $lyric->id]) }}"
                        class="btn btn-sm btn-info">Editar</a>

                    <form action="{{ route('authlyrics.destroy', ['lyric' => $lyric->id]) }}" method="POST"
                        class="d-inline" onsubmit="return confirm('Tem certeza que deseja excluir este usuário?')">
                        @method('DELETE')
                        @csrf
                        <input type="submit" value="Excluir" class="btn btn-sm btn-danger">
                    </form>
                </td>
            </tr>
            @endforeach
        </tbody>
    </table>
</div>
</div>
{{ $lyrics->links() }}
@endsection

**

路线 - web.php

**

/* Lyrics Routing for Auth'd User */
Route::resource('/authlyrics', 'Admin\LyricIdController');

**

歌词模型 - Lyric.php

**

class Lyric extends Model
{
protected $guarded = ['id', 'created_at', 'updated_at'];
protected $fillable = ['user_id', 'singer_id','title', 'info', 'video_url', 'lyric'];

public function singer()
{
    return $this->belongsTo(Singer::class)->withTimestamps();
}

public function user()
{
    return $this->belongsTo(User::class);
}
}

用户模型 - User.php

public function lyrics()
{
    return $this->hasMany(Lyric::class);
}

**

歌词控制器 - LyricIdController

**

class LyricIdController extends Controller
{
public function __construct(){
    $this->middleware('auth');
}

/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */

public function index()
{
    $user_id = Auth::user()->id;

    $lyrics = Lyric::where('user_id','=',$user_id)->orderBy('lyric', 'ASC')->paginate('10');

    return view('admin.userlyrics.index', [
        'lyrics' => $lyrics,
    ]); 
}

/**
 * Show the form for creating a new resource.
 *
 * @return \Illuminate\Http\Response
 */
public function create()
{
    return view('admin.userlyrics.create');
}

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    $data = $request->only([
        'title',
        // 'artist',
        'info',
        'video_url',
        'lyric'
    ]);

    $data['slug'] = Str::slug($data['title'], '-');
    $data['user_id'] = Auth::user()->id;

    $validator = Validator::make($data, [
        'title' => ['required', 'string', 'max:100'],
        'slug' => ['required', 'string', 'max:100', 'unique:lyrics'],
        // 'artist' => ['required', 'string', 'max:200'],
        'info' => ['string', 'max:100'],
        'video_url' => ['required', 'string', 'max:100', 'unique:lyrics'],
        'lyric' => ['required', 'string'],
    ]);

    if ($validator->fails()) {
        return redirect()->route('authlyrics.create')
            ->withErrors($validator)
            ->withInput();
    }

    // $artist = new Singer;
    // $artist->artist = $data['artist'];
    // $artist->save();

    $lyric = new Lyric;
    $lyric->user_id = $data['user_id'];
    $lyric->title = trim($data['title']);
    $lyric->slug = $data['slug'];
    $lyric->info = $data['info'];
    $lyric->video_url = $data['video_url'];
    $lyric->lyric = $data['lyric'];
    $lyric->save();

    Session::flash('message', 'Música adicionada com sucesso!');
    return redirect()->route('authlyrics.index');
}

/**
 * Display the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function show($id)
{
    $lyric = Lyric::find($id);

    return view('admin.userlyrics.show', [
        'lyric' => $lyric
    ]);
}

/**
 * Show the form for editing the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function edit($id)
{
    $lyric = Lyric::find($id);

    if ($lyric) {
        return view('admin.userlyrics.edit', [
            'lyric' => $lyric
        ]);
    }

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

/**
 * Update the specified resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function update(Request $request, $id)
{
    $lyric = Lyric::find($id);

    if ($lyric) {
        $data = $request->only([
            'title',
            // 'artist',
            'info',
            'video_url',
            'lyric'
        ]);

        if ($lyric['title'] !== $data['title']) {
            $data['slug'] = Str::slug($data['title'], '-');

            $validator = Validator::make($data, [
                'title' => ['required', 'string', 'max:100'],
                'info' => ['string', 'max:100'],
                'video_url' => ['required', 'string', 'max:100', 'url'],
                'slug' => ['required', 'string', 'max:100', 'unique:lyrics'],
                'lyric' => ['string'],
            ]);
        } else {
            $validator = Validator::make($data, [
                'title' => ['required', 'string', 'max:100'],
                'info' => ['string', 'max:100'],
                'video_url' => ['required', 'string', 'max:100', 'url'],
                'lyric' => ['string'],
            ]);
        }

        if ($validator->fails()) {
            return redirect()->route('authlyrics.edit', [
                'lyric' => $id
            ])
                ->withErrors($validator)
                ->withInput();
        }

        $lyric->title = trim($data['title']);
        $lyric->info = $data['info'];
        $lyric->video_url = $data['video_url'];
        $lyric->lyric = $data['lyric'];

        if (!empty($data['slug'])) {
            $lyric->slug = $data['slug'];
        }

        $lyric->save();
    }

    Session::flash('message', 'Música alterada com sucesso!');
    return redirect()->route('authlyrics.index');
}

/**
 * Remove the specified resource from storage.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function destroy($id)
{
    $lyric = Lyric::find($id);
    $lyric->delete();

    Session::flash('message', 'Música excluída com sucesso!');
    return redirect()->route('authlyrics.index');
}
}

**

歌词迁移

**

Schema::create('lyrics', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('user_id')->nullable();
        $table->string('video_url');
        $table->string('title');
        $table->string('info');
        $table->string('slug');
        $table->text('lyric');
        $table->timestamps();
        $table->engine = 'InnoDB';

        $table->foreign('user_id')
            ->references('id')
            ->on('users')
            ->onDelete('cascade');
    });

两个表,歌词和用户,都由外键绑定,但我似乎无法存储链接用户的歌词,也无法存储歌词。我需要某种 BIIIG 帮助...

标签: phpmysqllaraveleloquent

解决方案


用户.php

/**
 * The lyrics that belong to the user.
 *
 * @return BelongsToMany
 *
 */
public function lyrics()
{
    return $this->hasMany(Lyric::class);
}

歌词.php

/**
 * The user that owns to the lyrics.
 *
 * @return BelongsTo
 *
 */
public function user()
{
    return $this->belongsTo(User::class);
}

一旦你建立了关系,你就可以得到这样的歌词:

$user = auth()->user();  // Get the authenticated user.
$user->lyrics;

或者

$lyrics = auth()->user()->lyrics;

要将它们传递给您的视图:

$lyrics = auth()->user()->lyrics;

return view('my.view', compact('lyrics');

如果您正在使用路由模型绑定,则可以更新您的show()方法:

public function show(Lyric $lyric)
{
    return view('admin.userlyrics.show', compact('lyric');
}

您的路线可能类似于:

Route::get('lyrics/{lyric}', 'LyricController@show');

无论如何,您始终可以使用auth()->user(). 从那里,您应该可以访问这些关系。希望这可以帮助!

更新

这是您的store方法可能的样子。您可能需要对其进行一些调整以满足您的需求,但这应该会让您继续前进。

public function store(Request $request) {

    // Validate the request data.
    $attributes = $request->validate([
        'title' => 'required',
    ]);

    // Create a new Lyric instance and fill all of the fillable attributes.
    $lyric = new Lyric($attributes);

    // Populate anything that is not mass-assignable.
    $lyric->user_id = auth()->user()->id; // set things you want to be in control of.
    $lyric->slug = strtolower($request->title);  // example.

    ...

    $lyric->save();
}

推荐阅读