How to retrieve converted image in Spatie laravel-medialibrary? - laravel

I'm uploading images using the spatie media library and the images get uploaded and converted successfully. When accessing an uploaded image as below it works:
#foreach ($articles as $article)
<h1>{{ $article->title }}</h1>
<img src="{{ $article->getFirstMediaUrl() }}" alt="">
#endforeach
How can I access the converted images? I think I'm missing something from the documentation to make it work.
My model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
class Article extends Model implements HasMedia
{
use HasFactory, InteractsWithMedia;
protected $fillable = ['title'];
public function registerMediaConversions(Media $media = null): void
{
$this->addMediaConversion('thumb')
->width(250)
->height(90);
}
}
My store function
public function store(Request $request)
{
$file = $request->file('image');
$article = Article::create(['title' => 'First title']);
$article->addMedia($file)->toMediaCollection();
return back();
}

you should use getUrl() method to access the media url, so change your template like this.
<img src="{{ $article->getFirstMediaUrl()->getUrl() }}" alt="">
you will get the converted file perhaps if you want to access other object you can use other library function though from the document
https://spatie.be/docs/laravel-medialibrary/v10/introduction

Related

questions regarding laravel sidebar

im new to laravel and i want to know how to make a dynamic sidebar.
Right now it looks like this
In my native language it means category - berrys, juice, candy - and each of them goes to a view, where there should be only products who have in the database one of these three in the "category" column.
My question are:
1)Can i do it with a foreach loop?
2)Do i need to make a model and controller for each of them and if i do what functions do i need?
3)How do i show only the produkcts that have the right category
Right now i have:
#foreach($products as $item)
<div class="col-sm-6 col-md-4">
<a href="details/{{$item['id']}}">
<div class="thumbnail">
<img src="images/{{$item['galerija']}}" alt="...">
<div class="caption">
<h3>{{$item['nosaukums']}}</h3>
<p>{{$item['cena']}}</p>
</div>
</div>
</a>
</div>
#endforeach
That shows every product. Do i need something similar?
More details.
In my controller:
function shop()
{
$data= Product::all();
return view('pages.shop',['products'=>$data]);
}
My moddel:
class Product extends Model{
protected $primaryKey = 'id';
public $timestamps = false;
protected $fillable = [
'nosaukums', 'cena', 'kategorija', 'galerija', 'apraksts',
];
}
Yes.
Since it's the same model, you only need one controller with one method (if you follow conventions this would be a show method).
Using a relation.
Due to the fact you're coding in your native language (which I cannot decipher), below example is a way of how you could do it.
P.S. In the case that a product can have more than one categories, you should convert the relation into a Many to Many using a pivot table.
Category model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
public function products(): HasMany
{
return $this->hasMany(Product::class);
}
}
Product model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
public function category(): BelongsTo
{
return $this->belongsTo(Category::class);
}
}
Web.php
Route::get('categories/{category}', [CategoryController::class, 'show'])->name('categories.show');
Sidebar view
Note: You can load $categories using a View Composer.
<div>
#foreach($categories as $category)
<a href="{{ route('categories.show', compact('category')) }}">
{{ $category->name }}
</a>
#endforeach
</div>
Category controller
<?php
namespace App\Http\Controllers;
use App\Models\Category;
class CategoryController extends Controller
{
public function show(Category $category)
{
$products = $category->products;
return view('categories.show', compact('products');
}
}

why i already import this Error: "App\cat" not found

There is a relationship between the 2 models. And I want to display category name instead of category_id in show.bade.php. I am getting a this error.
Post model
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use App\cat;---- this is my cat model
class post extends Model
{
use HasFactory;
protected $table = 'posts';
protected $fillable = [
'post_name',
'post_content',
'name',
'status',
'file_path',
'slug',
'game_category_id'
];
public function cat(){
return $this->belongsTo(cat::class);
}
cat model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use App\post;------this is my post model
class cat extends Model
{
use HasFactory;
protected $table = 'cats';
protected $fillable = ['name','slug'];
public function post(){
return $this->hasMany(Post::class);
}
There is a relationship between the 2 models. And I want to display category name instead of category_id in show.blade.php. I am getting a this error.
Blade.php
#foreach($posts as $post)
<tr>
<th scope="row">{{$post->id}}</th>
<td><img src="{{asset('img/') . '/' .$post->file_path}}" width="100px " height="50px" class="img_table"></td>
<td>{{$post->post_name}}</td>
<td>{{$post->name}}</td>
<td>
#if(strcmp($post->status , 'Published') == 0)
<div class="btn btn-success">{{$post->status}}</div>
#else
<div class="btn btn-warning">{{$post->status}}</div>
#endif </td>
<td>{{$post->created_at->diffForHumans()}}</td>
<td>{{$post->slug}}</td>
<td>{{$post->cat->name}}</td>
<td><i class="far fa-edit"></i></td>
<td><i class="far fa-trash-alt"></i></td>
</tr>
#endforeach
$post->cat->name is this right way to call cat name instead of category id
Post Controller
namespace App\Http\Controllers;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Models\post;
use Validator;
public function list(){
$posts = Post::with('cat')->get();
$carbon = Carbon::now();
return view('layout.show', compact('posts'),['carbon' => $carbon]);
}
Since Laravel 8 the default namespace for models is App\Models. So use App\cat; should be use App\Models\cat;.
But you don't have to specify that since both post and cat are in the same namespace. You can just get rid of that line and it should still work.
By the way, Laravel's naming convention for models is to use CamelCase. So I'd stick with that unless you have a specific reason not to do so.
you have to change App\cat to App\Models\cat this will work...
and next.. that line you write <td>{{$post->cat->name}}</td> this will occur error,[Attempt to read property "name" on null] you changed to use separate foreach loop..
#foreach($post->cat as cat)
<td>{{$cat->name}}</td>
#endforeach
This will work for you ...

Eloquent model object not recognized_ laravel course excerice

Following an online course on Laravel I got stuck, and I do not see what I am doing wrong.
Can anyone see what I am doing wrong?
I have the following code in my project:
web.php
Route::get('/', function () {
return view('welcome');
});
Route::get('/pizzas', 'PizzaController#index');
Route::get('/pizzas/{id}','PizzaController#show');
Pizza.php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Pizza extends Model
{
use HasFactory;
// protected $tabel = 'pizzas';
}
PizzaController.php:
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\Pizza;
class PizzaController extends Controller
{
//
public function index(){
$pizzas = Pizza::all();
return view('pizzas', [
'pizzas'=>$pizzas,
]);
}
public function show($id){
return view('details', ['id'=> $id]);
}
Pizza.blade.php:
<h1> Pizza List </h1>
#foreach($pizzas as $pizza)
<div>
{{ $pizza->$name }} // HERE IS WHERE THE ERROR OCCURS
</div>
#endforeach
Error message:
ErrorException
Trying to get property '' of non-object (View: D:\xxxxxxxxxxx\laravel\pizzahouse1\resources\views\pizzas.blade.php)
http://localhost:8000/pizzas
error in line 21
<h1> Pizza List </h1>
#foreach($pizzas as $pizza)
<div>
{{ $pizza->$name }} // HERE IS WHERE THE ERROR OCCURS
</div>
#endforeach
Why you are using "$name"?
Error says ,
You are calling for a property that doesn't exists in $pizza.
it should be something like following:
{{ $pizza->name }}
If problem still exists just :
dd($pizza);
Then see the results and call the property.
Hope it would help.

Class 'Photo' not found from within view

I'm working on a photography website at the moment and am having trouble with the page that should show all the albums and pictures within the album. I always get an error
Class 'Photo' not found (View: /var/www/photography.website/resources/views/album/index.blade.php)
when trying to access the page.
Following are the view, controllers, and models;
Index View:
#extends('layout.main')
#section('title')
<title>Albums</title>
#endsection
#section('content')
<div class="content">
#if(count($albums)==0)
<p>Nothing here yet, come back later!</p>
#else
#foreach($albums as $album)
<div class="album">
<h3>{{$album->name}}</h3>
#foreach($album->photos()->getEager() as $photo)
<img src="/public/thumb-{{$photo->id->toString()}}.jpeg" class="">
#endforeach
</div>
</div>
#endforeach
#endif
#endsection
Album Controller (snippet):
<?php
namespace App\Http\Controllers;
use App\Photo;
use App\Album;
use Illuminate\Http\Request;
class AlbumController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$albums = Album::all();
return view('album.index')->with(compact($albums));
}
}
Album Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Album extends Model
{
protected $fillable = ['name','cover'];
public function photos() {
return $this->hasMany('Photo');
}
}
Photo Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Photo extends Model
{
public $incrementing = false;
protected $fillable = ['id','album_id','title'];
}
You are using the Unqualified Name of the class in your relationship. You would need to use the full name of the class when referring to the class via string like that.
There is no class named Photo in the application but there is a class named App\Photo.
public function photos() {
return $this->hasMany('App\Photo');
// but probably almost always better to use the class constant
return $this->hasMany(Photo::class);
// 'App\Photo'
}
Photo here refers to a class in the current namespace App, as there is no alias for anything named Photo.

Trying to get property of non-object in Laravel Relationship

I have two tables in my database, an Articles table and a Users table. An Article is posted by a user and a foreign key exists called 'created_by' referring to the 'user_id' field in the Users table.
My Laravel models are as follows:
User model
class User extends Model
{
use Notifiable;
protected $primaryKey = 'user_id';
public function articles()
{
return $this->hasMany('App\Article', 'created_by', 'user_id');
}
}
Article Model
class Article extends Model
{
protected $primaryKey = 'article_id';
public function user()
{
return $this->belongsTo('App\User', 'created_by' 'user_id');
}
}
I have a view dashboard which displays all the articles and the name of the person who posted it and their image.
Dashboard Controller
<?php
namespace App\Http\Controllers;
use App\User;
use App\Article;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class DashboardController extends Controller
{
public function index (Request $request)
{
if($request->session()->get('username')) {
$articles = Article::all();
return view('dashboard', compact('articles'));
}
else
return redirect('login');
}
}
And finally the section of my view I'm getting the 'Trying to get property of non-object' error for.
#foreach($articles as $article)
<div class="row">
<div class="col-lg-1"></div>
<div class="col-lg-9">
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-title">{{ $article->title }} </h3>
</div>
<div class="panel-body">
<p>
{{ $article->content }}
<br><br> - {{ $article->user->first_name }}
</p>
</div>
</div>
</div>
<div class="col-lg-1"><center><br><br>
<img src="{{ asset('images/people/$article->user->image') }}" class="img-circle" alt="Person"></center>
</div>
</div><br><br>
#endforeach
It seems to be the $article->user->first_name that I am having trouble with. If I type $article->user alone, the page will load but nothing appears in that area.
Any ideas, I have been searching for solutions for the last two hours.
I think you need to specify that you want users to load with with the articles, like $articles = Article::with('user')->all();
Drop a dd($articles) right before the return statement and you'll see what you're actually dealing with.
$articles = Article::with('user')->get();
Edit
Try to check also if $article->user is null in the view because if there is no user assigned for an article then you will get "trying to get property of non object" error
so give an extra check when you access user's data.
{{ $article->user !== null ? $article->user->first_name : 'User Not Found' }}
Do this for user photo also
Please edit your controller, pls mark as answered thx.
<?php
namespace App\Http\Controllers;
use App\User;
use App\Article;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class DashboardController extends Controller
{
public function index (Request $request, Article $articles)
{
if($request->session()->get('username')) {
return view('dashboard')->with('articles', $articles->all() );
}
else
return redirect('login');
}
}

Resources