Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving and displaying a single record from database in laravel

I have two methods in my controller. The first is called uploads and it displays all the records from a DB table, it looks like this :

 public function uploads()
    {
        //return Upload::all();
        $uploads = Upload::all();
        return view('uploads')->with('uploads',$uploads);
    }

This function is working and all the records are successfully retrieved in my view.

The issue is with the second method upload which aims to show a data for a single upload when its name is clicked from the list of uploads.

Currently, I have just this :

 public function upload($id)
{
    return Upload::find($id);
}

And I am not sure how to complete this functionality.

My view is looking like this :

 @extends('layouts.app')
@section('content')
    <h1>Uploads</h1>
    @if(count($uploads)>0)
@foreach($uploads as $upload)
    <div class="well">
        <h3><a href="/uploads/{{$upload->id}}">{{$upload->name}}</a> </h3>
        <small>Written on {{$upload->created_at}}</small>
    </div>
        @endforeach
    @else
    <p>No uploads found</p>
    @endif

@endsection

I wasn't really sure what to put in web.php, so my routes look like this :

    Route::get('/uploads', function () {
    return view('uploads');
});

Auth::routes();
Route::get('/uploads','UploadController@uploads')->name('uploads');

Can someone help me make this work? I just want to see the associative array with the record from the database when I click on an upload's name. What do I need to add in routes and in my view?

like image 616
incense_stick Avatar asked Oct 18 '22 02:10

incense_stick


1 Answers

// Controller
public function uploads()
{
    $uploads = Upload::all();
    return view('uploads')->with('uploads', $uploads);
}

You can use Laravels IOC container here and let Laravel pass the correct Upload in your controller action.

public function showUploadDetail(Upload $upload)
{
    return view('uploadDetail')->with('upload', $upload);
}

Create a new blade file called uploadDetail.blade.php with the sample content:

@extends('layouts.app')

@section('content')
   <h1>Upload Detail</h1>
   <p>ID: {{ $upload->id }}</p>
@endsection

And as already mentioned by fil adjust your route to:

Route::get('/upload/{id}', 'UploadController@upload')->name('upload');
like image 121
common sense Avatar answered Oct 21 '22 00:10

common sense