简体   繁体   中英

Laravel - Data storing/fetching for current logged user

I am trying to store and fetch the data for current logged user in laravel but I am not getting anything besides errors

[

Missing required parameters for [Route: authlyrics.show] [URI: painel/authlyrics/{authlyric}]. (View: /var/www/html/allup_lyrics_cms/resources/views/admin/userlyrics/index.blade.php)

]

I mean that I have two tables. One is users table which stores the data for login and other table is lyrics table, which stores lyrics the user will add to the site. How can I store this authenticated user lyrics and fetch the lyrics to list them in the index page? while lyrics and users are bound through user_id foreign key. My code is given here:

**

Lyrics List - 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

**

Route - web.php

**

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

**

Lyric Model - 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 Model - User.php

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

**

Lyric Controller - 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');
}
}

**

Lyrics Migration

**

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');
    });

Both tables, lyrics and users, are bound by foreign key but I don't seem to get to store the lyrics linking the user and feth the lyrics as well.. I need some sort of a BIIIG help please...

User.php

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

Lyric.php

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

Once you've got the relationships, you can get to the lyrics like this:

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

or

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

To pass them to your view:

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

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

If you are using route model binding, you can update your show() method:

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

Your route might look something like:

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

In any event, you can always get the current user with auth()->user() . From there, you should have access to the relationships. Hope this helps!

UPDATE

Here's what your store method might look like. You may need to tweak it a bit to fit your needs, but this should get you going.

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM