i have the images field in Articles table and i will save all images into this field as array : images/image1.jpg,images/image2.jpg, ...
in my index page, i am getting all articles and show them in home page :
$articles = \App\Article::all();
i want to just load first image from every article as cover image and show that but the images field is string. what can i do?
#foreach($articles as $article)
<div class="article_wrapper">
<div class="article_body">
#foreach($article->images as $image)
{{ $image }}
#endforeach
</div>
</div>
#endforeach
Using a route only:
Route::any('/article/images/{id}', ['as' => 'article.image', function($id) {
$article = Article::find($id);
$images = explode(',',$article->images);
return Response::download($images[0]);
}]);
Using a controller:
namespace MyNamespace;
use Illuminate\Routing\Controller;
use App\Article;
use Response;
class ImagesController extends Controller
{
public function show($id)
{
$article = Article::find($id);
$images = explode(',',$article->images);
return Response::download($images[0]);
}
}
Your route:
Route::get('/article/images/{id}', ['as' => 'article.image', 'uses' => 'MyNamespace\ImagesController#show']);
Then in your view:
<img src="{{route('article.image', ['id' => $article->getKey()])}}" />
So that your view will look like:
#foreach($articles as $article)
<div class="article_wrapper">
<div class="article_body">
<img src="{{route('article.image', ['id' => $article->getKey()])}}" />
</div>
</div>
#endforeach
If you aren't saving the fullpath in the images field then prefix it:
return Response::download('C:\downloadpath\' . $images[0]);
Related
I have a DB with multiple tables. I want to display the DB data on my laravel application. I want to display two tables data on the same page. I have created the model, view, and controller for the app but I am being able to display only one table. I cannot show the other table.
I think I need to define a model with multiple relationships which I am not getting how to do.
My tables are called posts and videos I have nothing on my model. the controller and the view is given below.
Controller
namespace App\Http\Controllers;
use App\Post;
use App\Video;
use Illuminate\Http\Request;
class PostsController extends Controller
{
public function index()
{
$posts = Post::all();
return view('landing')->with('posts', $posts);
}
}
View
#extends('layouts.app')
#extends('layouts.navbar')
#section('title')
Landing Page
#endsection
#section('content')
<main class="py-4">
<div class="container">
<div class="row">
<div class="col-md-8">
<h3>Section 1</h3>
#foreach ($posts as $post)
<ul class="list-group">
<li class="list-group-item">
<a href="/posts/{{ $post->id }}">
{{ $post->title }}
{{ $post->brief }}
{{ $post->body }}
{{ $post->cover_image }}
</a>
</li>
</ul>
#endforeach
</div>
<div class="col-md-4">
<h3>Section 2</h3>
#foreach ($videos as $video)
<ul class="list-group">
<li class="list-group-item">
<a href="/videos/{{ $video->id }}">
{{ $video->title }}
</a>
</li>
</ul>
#endforeach
</div>
</div>
</div>
</main>
#endsection
Route on the web.php
<?php
use App\Http\Controllers\PagesController;
use Illuminate\Support\Facades\Route;
Route::get('/', 'PostsController#index');
Route::get('/', 'VideosController#index');
Route::get('/posts/{post}', 'PostsController#show');
Route::resource('posts', 'PostsController');
Route::resource('videos', 'VideosController');
Auth::routes();
Controller for videos data table
<?php
namespace App\Http\Controllers;
use App\Video;
use Illuminate\Http\Request;
class VideosController extends Controller
{
public function index()
{
$videos = Video::all();
return view('landing')->with('videos', $videos);
}
}
On this code I see this problem
If I remove the route for videos on my web.php I could see posts data.
So how could I display both the posts and the videos data at the same time?
Pass both Model together :
<?php
namespace App\Http\Controllers;
use App\Video;
use App\Post;
use Illuminate\Http\Request;
class VideosController extends Controller
{
public function index()
{
$videos = Video::all();
$posts = Post::all();
return view('landing', compact('videos','posts'));
}
}
public function profile($id)
{
$id = Crypt::decrypt($id);
$measurements = DB::select( DB::raw("SELECT * FROM measurements WHERE custom_id = '$id'") );
$customers = DB::table('customers')->where('customer_id', '=', $id)->get();
return view('measurements.profile', compact('measurements','customers'));
}
I am trying to get the posts that belong to each category, i had this working before but i can't seem to find what i have done wrong here.
I have a Post Table and a Categories Table
ROUTE
Route::get('articles/category/{id}', ['as' => 'post.category', 'uses' => 'ArticlesController#getPostCategory']);
CONTROLLER
public function getPostCategory($id)
{
$postCategories = PostCategory::with('posts')
->where('post_category_id', '=', $id)
->first();
$categories = PostCategory::all();
// return view
return view('categories.categoriesposts')->with('postCategories', $postCategories)->with('categories', $categories);
}
VIEW
#foreach($postCategories->posts as $post)
<div class="well">
<div class="media">
<a class="pull-left" href="#">
<img class="media-object" src="http://placekitten.com/150/150">
</a>
<div class="media-body">
<h4 class="media-heading">{{ substr($post->title, 0, 50) }}</h4>
<p class="text-right">By Francisco</p>
<p>{{ substr($post->body, 0, 90) }}</p>
<ul class="list-inline list-unstyled">
</ul>
</div>
</div>
</div>
#endforeach
POST MODAL
public function postCategory()
{
return $this->belongsTo('App\PostCategory');
}
POSTCATEGORY MODAL
class PostCategory extends Model
{
// connect Categories to Posts tables
protected $table = 'post_categories';
// Category belongs to more than 1 post
public function posts()
{
return $this->hasMany('App\Post', 'post_category_id');
}
}
I can't see what i am doing wrong every time I go to a category it shows
Trying to get property of non-object
Any help will be much appreciated thanks
replace your lines:
$postCategories = PostCategory::with('posts')
->where('post_category_id', '=', $id)
->first();
with:
$postCategories = PostCategory::find($id)->posts;
Change your line in your PostCategoryModel to:
return $this->hasMany('App\Post', 'post_category_id','post_category_id');
New to Laravel and feel that I'm missing something important here. I am uploading and saving multiple files to a folder and saving an array of the images names to the database(simple enough). Currently saving the images name in the json_encode() format so they are formatted like so["kittyTest.jpeg","kitty_2.jpeg","kitty_3.jpeg"]. So when I try and print them out to the view I get them in the json format and am trying to display them in an array formate or in some way that I can use the filename for the source image. Any help or guidance would be much appreciated.
Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Form;
use DB;
class FormController extends Controller
{
public function index()
{
$images = DB::select('select * from forms');
//dd(json_decode($images[0]->filename));
return view('index', ['images'=> $images]);
}
public function create()
{
return view('create');
}
public function store(Request $request)
{
$this->validate($request, [
'filename' => 'required',
'filename.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
if ($request->hasFile('filename')) {
foreach ($request->file('filename') as $image) {
$name = $image->getClientOriginalName();
$image->move(public_path().'/images/', $name);
$data[] = $name;
}
}
$form = new Form();
$form->filename = json_encode($data);
$form->save();
return back()->with('success', 'Your images have been uploaded');
}
}
View
<body>
<div class="container">
<h3 class="jumbotron">Laravel Multiple File Upload</h3>
<p>Here are the images we have in the database</p>
<ul class="list-group">
#foreach ($images as $image)
<li class="list-group-item">
{{ $image->filename }}
</li>
#endforeach
</ul>
</div>
</body>
<ul class="list-group">
#foreach ($images as $image)
#php $image_array = json_decode($image->filename,true); #endphp
#foreach ($image_array as $img)
<li class="list-group-item">
{{ $img }}
</li>
#endforeach
#endforeach
</ul>
try this and let me know
In your controller use array_map to json_decode every image filenames and then use second foreach in your view file.
Controller
public function index()
{
$images = DB::select('select * from forms');
array_map(function($a) {
$a->filename = json_decode($a->filename);
return $a;
}, $images);
return view('index', compact($images)); // you can use compact function here
}
View
<ul class="list-group">
#foreach ($images as $image)
<li class="list-group-item">
#foreach ( $image->filename as $file)
{{ $file }}
#endforeach
</li>
#endforeach
</ul>
Edit: You can also try cast to array, then you dont need to worry about mapping it in your controller file.
This is AdminController.php:
<?php
namespace App\Http\Controllers;
use Response;
use Illuminate\Support\Facades\DB;
use App\Caption;
use App\Image;
use App\Http\Controllers\Controller;
class AdminController extends Controller
{
public function admin() {
$images = Image::paginate();
return view('admin',[ '$images' => $images]);
}
}
And this is admin.blade.php:
#extends('template')
#section('title')
Admin Page
#endsection
#section('header')
#endsection
#section('main')
#if (Auth::check())
#foreach ($images as $image)
<p value='{{$image->id}}'>{{$image->content}}</p>
<form action="image/{{$image->id}}/delete" method="post">
<button type="submit">Delete caption</button>
</form>
<form action="image/{{$image->id}}/approve" method="post">
<button type="submit">Accept image</button>
</form>
#endforeach
#else
<p>Login first</p>
#endif
#endsection
#section('footer')
#endsection
Why do I get the following error?
ErrorException in 408148d5409ae6eebf768dc5721bd0d1d9af48af.php line 9:
Undefined variable: images (View: /Users/sahandz/Documents/School/Singapore/CS3226/backend/resources/views/admin.blade.php)
$imagesis clearly defined in my controller.
You have used $images as your variable name when passing the data to the view. This results in blade creating a variable called $$images.
return view('admin',[ 'images' => $images]);
will result in the view creating a variable called $images
Try passing data like this.
$images = Image::paginate();
return view("admin")->with('images',$images);
Basically,you need not use $ in the variable name.
Your code should be like this
public function admin() {
$images = Image::paginate();
return view('admin',[ 'images' => $images]);
}
Why you use [ '$images' => $images]. that is the problem.
You may use this method also to pass your data to view
return view('admin',compact('images'));
I'm trying to pass the getMonth view via the route but doens't seem be working as it shows all results from my db when the $month is specified instead of filtering the results by month. However $id does work and will go to a single post matching the $id from the db.
Route::get('blog', ['as' => 'blog', 'uses' => 'BlogController#BlogIndex']);
Route::get('blog/{Id}', ['as' => 'blog.id', 'uses' => 'BlogController#ShowbyId']);
Route::get('blog/month/{month}', ['as' => 'blog.month', 'uses' => 'BlogController#ShowbyMonth']);
class BlogController extends BaseController {
public function BlogIndex()
{
//get the posts from the database by asking the Active Record for "all"
$blogs = Blog::all();
$blogs = DB::table('blogs')->paginate(3);
// and create a view which we return - note dot syntax to go into folder
return View::make('pages.blog', array('blogs' => $blogs));
}
public function ShowbyId($Id)
{
$Ids = Blog::where('Id', '=', $Id)->get();
// show the view with blog posts (app/views/pages/blog.blade.php)
return View::make('pages.blog')
->with('Ids', $Ids)
}
public function ShowbyMonth($month)
{
$months = Blog::where('month', '=', $month)->get();
// show the view with blog posts (app/views/pages/blog.blade.php)
return View::make('pages.blog')
->with('months', $months)
}
}
blog.blade.php
#if(isset($blogs))
#foreach ($blogs as $blog)
<div class="blog-outer-wrap">
<img src="images/blog/{{ $blog->img}}">
<div class="blog-header">{{ $blog->header }}</div>
<div class="blog-text">{{ $blog->content }}</div>
<a href="{{ URL::route('blog.slug', [$blog->slug]) }}">
</div>
#endforeach
#elseif(isset($Ids))
#foreach ($Ids as $Id)
<div class="blog-outer-wrap">
<img src="images/blog/{{ $Id->img}}">
<div class="blog-header">{{ $Id->header }}</div>
<div class="blog-text">{{ $Id->content }}</div>
</div>
#elseif(isset($months))
#foreach ($months as $month)
<div class="blog-outer-wrap">
<img src="images/blog/{{ $Month->img}}">
<div class="blog-header">{{ $Month->header }}</div>
<div class="blog-text">{{ $Month->content }}</div>
</div>
#endif
#endforeach
I'm not sure if it solves the problem but in blade file you have:
#elseif(isset($months))
#foreach ($months as $month)
<div class="blog-outer-wrap">
<img src="images/blog/{{ $Month->img}}">
<div class="blog-header">{{ $Month->header }}</div>
<div class="blog-text">{{ $Month->content }}</div>
</div>
#endif
and it should be rather:
#elseif(isset($months))
#foreach ($months as $Month)
<div class="blog-outer-wrap">
<img src="images/blog/{{ $Month->img}}">
<div class="blog-header">{{ $Month->header }}</div>
<div class="blog-text">{{ $Month->content }}</div>
</div>
#endif
You should care about variables case.
The problem I see is your URI/route structure, you currently have this:
Route::get('blog/{Id}', ['as' => 'blog.id', 'uses' => 'BlogController#ShowbyId']);
Route::get('blog/month/{month}', ['as' => 'blog.month', 'uses' => 'BlogController#ShowbyMonth']);
Whenever you try to access the blog.month route blog.id is receiving the word month. It may be better to put the month route first, so that the month URI is hit before the ID route.
Route::get('blog/month/{month}', ['as' => 'blog.month', 'uses' => 'BlogController#ShowbyMonth']);
Route::get('blog/{id}', ['as' => 'blog.id', 'uses' => 'BlogController#ShowbyId']);
Also, to clean up your controller you may consider using a query scope to make your logic more reusable and easier to debug. In your model you could do something like this:
class Blog extends Eloquent {
public function scopeMonth($query, $month) {
return $query->where('month', '=', $month);
}
}
Then in your Controller you could do this:
class BlogController extends BaseController {
//.. BlogIndex here
public function ShowbyId($Id)
{
$blog = Blog::find($id)->get();
// show the view with blog posts (app/views/pages/blog.blade.php)
return View::make('pages.blog')
->with('Ids', $blog);
}
public function ShowbyMonth($month)
{
$months = Blog::month($month)->get();
// show the view with blog posts (app/views/pages/blog.blade.php)
return View::make('pages.blog')
->with('months', $months)
}
}
Hopefully this helps!