Laravel Excel to export data will download empty data with only headers in excel sheet! I want to export only the filtered data from my search using excel but it will download an empty excel sheet only with headers!! please can anyone tell me where is my error!
DealerExportSearch.php
class DealersSearchExport implements FromCollection, WithHeadings, ShouldAutoSize, WithEvents
{
use Exportable;
protected $name;
protected $email;
protected $mobile_no;
protected $city;
public function __construct( $name, $email, $mobile_no , $city)
{
$this->name = $name;
$this->email = $email;
$this->mobile_no = $mobile_no;
$this->city = $city;
}
//function select data from database
public function collection()
{
return Dealer::select()->where('name', $this->name)
->where('email', $this->email)
->where('mobile_no', $this->mobile_no)
->where('city', '=', $this->city) //i tried using the above and this also same result
->get();
}
public function registerEvents(): array
{
return [
AfterSheet::class => function (AfterSheet $event) {
$cellRange = 'A1:W1'; // All headers
$event->sheet->getDelegate()->getStyle($cellRange)->getFont()->setSize(12);
},
];
}
//function header in excel
public function headings(): array
{
return [
'No',
'name',
'email',
'mobile_no',
'shop_name',
'city',
'address'
];
}
}
my controller
public function index(Request $request)
{
$method = $request->method();
if ($request->isMethod('get')) {
$name = $request->name;
$email = $request->email;
$city = $request->city;
$mobile_no = $request->mobile_no;
if ($request->has('search')) {
$dealers = Dealer::where('name', 'LIKE', '%'.$name.'%')
->where('email', 'LIKE', '%'.$email.'%')
->where('mobile_no', 'LIKE', '%'.$mobile_no.'%')
->where('city', 'LIKE', '%'.$city.'%')
->paginate(5);
return view('dealer.index', compact('dealers'));
}
elseif ($request->has('exportSearchExcel')) {
return Excel::download(new DealersSearchExport($name ?? '', $email ?? '', $mobile_no ?? '', $city ?? ''), 'DealersSearchExcel-reports.xlsx');
}
else{
$dealers = Dealer::orderBy('id', 'DESC')->paginate(5);
return view('dealer.index', compact('dealers'));
}
}
}
blade
<form action="{{ route('dealer.index') }}" method="GET" enctype="multipart/form-data">
#csrf
<div class="form-group row">
<div class="col-sm-3">
<label for="name">Name: </label>
<input class="form-control" name="name" value="{{ request()->input('name') }}" type="text" placeholder="The Dealer Name">
</div>
.....................................................................
</div>
<div class="col-md-12 pt-3 text-right">
<button type="submit" name="search" class="btn btn-primary"><i class="fa fa-fw fa-search"></i> Search</button>
<button type="submit" name="exportSearchExcel" class="btn btn-secondary text-light"><i class="fa fa-download"></i> Export Excel </button>
</div>
</div>
No error is showing just in my console it will return this error and download an empty xslx whenever I press the export button.
Resource interpreted as Document but transferred with MIME type application/vnd.openxmlformats-officedocument.spreadsheetml.sheet: "http://127.0.0.1:8000/dealer?_token=TTlpqFNn4hr5rwI1jSlt0d4mbtww2moO8i1WWjfn&name=&email=&mobile_no=&exportSearchExcel=".
Update
I fixed it by changing my query in DealerExportSearch.php to the same query that I have in controller then it worked
DealerExportSearch.php
class DealersSearchExport implements FromCollection, WithHeadings, ShouldAutoSize, WithEvents , WithMapping
{
//the above codes not changed till the collection function
//function select data from database
public function Collection()
{
return Dealer::where('name', 'LIKE', '%'.$this->name.'%')
->where('email', 'LIKE', '%'.$this->email.'%')
->where('mobile_no', 'LIKE', '%'.$this->mobile_no.'%')
->where('city', 'LIKE', '%'.$this->city.'%')
->get();
}
public function map($row): array{
$fields = [
$row->id,
$row->name,
$row->gender,
$row->date_of_birth,
$row->email,
$row->mobile_no,
$row->shop_name,
$row->city,
$row->address,
];
return $fields;
}
///below codes not changed .....
Related
CONTROLLER
public function store_resto(Request $request){
// dd($request->all());
$restaurant = new Restaurant();
$restaurant->name = $request->input('name');
$restaurant->email = $request->input('email');
$restaurant->address = $request->input('address');
$restaurant->save();
$image = $request->hasfile('image');
$photo = rand(1,9999).'.'.$image;
$path = public_path().'/files/';
$image->move($path, $photo);
RestoImage::create([
'image'=>$image,
'resto_id'=>$restaurant->id,
]);
$request->session()->flash('status', 'Restaurant added successfully');
return redirect('list');
}
VIEW FILE
<form method="post" action="{{route('store_resto')}}" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label>Resto Name</label>
<input type="name" name="name" class="form-control">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control">
</div>
<div class="form-group">
<label>Address</label>
<input type="text" name="address" class="form-control">
</div>
<div class="form-group">
<label>Image</label>
<input type="file" name="image" class="form-control">
</div><br>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
RestoImage Model
class RestoImage extends Model
{
use HasFactory;
protected $fillable = ['image','resto_id'];
public function restaurants(){
$this->belongsTo(Restaurant::class, 'resto_id');
}
}
Restaurant Model
class Restaurant extends Model
{
use HasFactory;
public $timestamps = false;
public function menus(){
$this->hasMany(Menu::class);
}
public function restoimage(){
$this->hasOne(RestoImage::class, 'resto_id');
}
}
Each restaurant will have 1 image. When an admin submits the form, 1 record should be inserted in both tables i.e. restaurants and resto_images. I tried this way but when I submit the form, It shows error "Call to a member function move() on bool". Please correct me if I am doing wrong. Thanks in advance.
Here i Worked on your code to explain how these things works.This is an example can help you. Not for two you can add so many tables from one function of controller. Approve my answer if you find solution or reason for getting error.
You have error because code doesn't find your image format or mine:type(png, jpeg)
$photo = rand(1,9999).'.'.$image;
Solution- you have to get image format or extention by this code
$extention = $emp_image_file->getClientOriginalExtension();
Your solution should be like this
$path1 = 'assets/img/emp/';
$destinationPath1 = $path1;
$photo_file = $request->file('image');
$photo='';
if($photo_file){
$file_size = $photo_file->getSize();
$image_name = $photo_file->getClientOriginalName();
$extention = $photo_file->getClientOriginalExtension();
$photo = value(function() use ($photo_file){
$filename = time().'.'. $photo_file->getClientOriginalExtension();
return strtolower($filename);
});
$photo_file->move($destinationPath1, $photo);
}
Put js in your view file
<script type="text/javascript">
function readURL(input) {
if (input.image && input.image[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#imagePreview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
</script>
This is you input
<input type="file" class="form-control" name="image" >
I Also Worked For Other Visitors See Once
public function store_resto(Request $request){
<!-- validation code begins -->
$this->validate($request, [
'name'=>'required|max:120',
'email'=>'required|email|unique:users',
]);
<!-- validation code ends -->
$data = $request->all();
$table1 = Required_Model1::create([
'name' =>$data['emp_name'],
'email' =>$data['email'],
]);
$table2 = Required_Model2::create([
'name' => $data['emp_name'],
'code' => $data['emp_code'],
'status' => $data['emp_status'],
'email' => $data['email'],
'gender' => $data['gender'],
'table1_id' => $table1->id,
]);
$table3 = Required_Model3::create([
'role' => $data['role'],
'table1_id' => $table1->id,
'table2_id' => $table2->id,
if(isset($table1, $table2, $table3)) {
$request->session()->flash('status', 'Restaurant added successfully');
return redirect()->route('employee-manager');
}else{
return redirect()->back();
}
}
Comment or delete this part of code if you doesn't want to validate or mandatory.
$this->validate($request, [
'name'=>'required|max:120',
'email'=>'required,
]);
Above code explains
column name must be filled with 120 characters or not be blank.
column email must be filled.
if these two doesn't satisfy it will redirect back.
This below code
If validation is set like above code this will check and work as defined. If validation is set they check two fields name and email, if they filled or not blank it will proceed further. If validation is set fields are not filled or blank they redirect back. If validation is not set it will proceed further.
if(isset($table1, $table2, $table3)) {
$request->session()->flash('status', 'Restaurant added successfully');
return redirect()->route('employee-manager');
}else{
return redirect()->back();
}
Change these two lines
<input type="name" name="name" class="form-control" required="true" />
<input type="email" name="email" class="form-control" required="true" />
Model 1 should be like this
class Required_Model1 extends Model
{
protected $fillable = ['name','email'];
}
Model 2 should be like this
class Required_Model2 extends Model
{
protected $fillable = ['name','code', 'status', 'email', 'gender', 'table1_id'];
}
Model 3 should be like this
class Required_Model3 extends Model
{
protected $fillable = ['role','table1_id', 'table2_id'];
}
Let's talk on your error as you posted
You have face error because you want to move your image name in form of boolean. Here is gave you an standard code you can use it
$path1 = 'assets/img/emp/';
$destinationPath1 = $path1;
$emp_image_file = $request->file('employee_images');
$emp_image='';
if($emp_image_file){
$file_size = $emp_image_file->getSize();
$image_name = $emp_image_file->getClientOriginalName();
$extention = $emp_image_file->getClientOriginalExtension();
$emp_image = value(function() use ($emp_image_file){
$filename = time().'.'. $emp_image_file->getClientOriginalExtension();
return strtolower($filename);
});
$emp_image_file->move($destinationPath1, $emp_image);
}
Put this in which table you wanted to save
'photo' => $emp_image,
Add this in your view make sure you edit like your requirement
<script type="text/javascript">
function readURL(input) {
if (input.employee_images && input.employee_images[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#employee_imagesPreview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
</script>
This is input
<input type="file" class="form-control" name="employee_images" >
$image = $request->hasfile('image');
This method is a boolean method. It will return true/false. Instead use
$request->file('image');
So first, here:
$image = $request->hasfile('image');
You are setting $image to a boolean by checking if it has that file and then later you want to run move on a that boolean which is not possible. Rather do:
if($request->hasfile('image'))
{
$image = $request->file('image');
$image->move($path, $photo);
}
I am getting this error when I try to submit the selected option using Laravel Livewire.
Illuminate\Database\QueryException
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'team_id' cannot be null (SQL: insert into projects (user_id, name, description, team_id, updated_at, created_at) values (1, Sammy Mwangangi, qdqwfdweqfc wqdqwfdwqdqwdwq, ?, 2021-06-24 13:39:14, 2021-06-24 13:39:14))
App\Models\Project.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
use HasFactory;
protected $fillable = [
'name',
'description',
'team_id',
];
// protected $guarded = [];
public function tasks(){
return $this->hasMany(Task::class);
}
public function user(){
return $this->belongsTo(User::class);
}
public function team(){
return $this->belongsTo(Team::class);
}
}
App\Http\Livewire\Project.php
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\Project;
use App\Models\Team;
use Livewire\WithPagination;
use Illuminate\Support\Str;
use Auth;
class Projects extends Component
{
use WithPagination;
public $name;
public $description;
public $team_id;
public $projectId = null;
public $showModalForm = false;
public function showCreateProjectModal()
{
$this->showModalForm = true;
}
public function updatedShowModalForm()
{
$this->reset();
}
public function storeProject()
{
$this->validate([
'name' =>'required',
'description' => 'required',
]);
$project =new Project();
$project->user_id = auth()->user()->id;
$project->name = $this->name;
$project->description = $this->description;
$project->team_id = $this->team_id;
$project->save();
$this->reset();
session()->flash('flash.banner', 'Project created Successfully');
}
public function showEditProjectModal($id)
{
$this->reset();
$this->showModalForm = true;
$this->projectId = $id;
$this->loadEditForm();
}
public function loadEditForm()
{
$project = Project::findOrFail($this->projectId);
$this->name = $project->name;
$this->description = $project->description;
}
public function updateProject()
{
$this->validate([
'name' =>'required',
'description' => 'required',
]);
Project::find($this->projectId)->update([
'name' => $this->name,
'description' => $this->description
]);
$this->reset();
session()->flash('flash.banner', 'Project Updated Successfully');
}
public function deleteProject($id)
{
$project = Project::find($id);
$project->delete();
session()->flash('flash.banner', 'Project Deleted Successfully');
}
public function render()
{
return view('livewire.projects', [
'projects' => Project::orderBy('created_at', 'DESC')->paginate(5),
'teams' => Team::all()
]);
}
}
projects.blade.php
<div class="flex flex-wrap mb-6">
<label for="team" class="block text-gray-700 dark:text-white text-sm font-bold mb-2">
{{ __('Team') }}:
</label>
<select class="form-select px-4 py-3 w-full rounded" wire:model="team_id" name="team_id">
#foreach($teams as $team)
<option value="{{$team->id}}">{{$team->name}}</option>
#endforeach
</select>
<p class="mt-2 text-sm text-gray-500">
Select the team/department your project is associated with.
</p>
#error('team_id')
<p class="text-red-500 text-xs italic mt-4">
{{ $message }}
</p>
#enderror
</div>
What am I missing? I haven't done much with livewire regarding model relationships and how to bind data between the models.
you must do a default tag option for select, this way on change element this will bind the value to the property
<select class="form-select px-4 py-3 w-full rounded" wire:model="team_id">
<option>Select Team</option>
#foreach($teams as $team)
<option value="{{$team->id}}">{{$team->name}}</option>
#endforeach
</select>
also in the validation rules you can add another for the "team_id" value that can't be null on submit
wire:model should be on option tag not on select
I have a livewire CRUD component to make posts. It worked perfectly before I tried to add a choice of categories. This is a piece of code, where I try to choose a category:
<select class="form-select" aria-label="Default select example">
<option wire:model="category_id" selected>Выберите категорию</option>
#foreach($categories as $category)
<option value="{{ $category->id }}">
{{ $category->name }}
</option>
#endforeach
#error('category_id') <span class="text-red-500">{{ $message }}</span>#enderror
</select>
I can display all the categories and choose one, but I can't get it in the component. I have tried to use a checkbox element. I was even validated, whenever I chose a category or not. The select field isn't validated at all. I can just output all the categories from the db.
Here is my CRUD component.
<?php
namespace App\Http\Livewire;
use App\Models\Category;
use Livewire\Component;
use App\Models\Post;
use Livewire\WithPagination;
use Livewire\WithFileUploads;
class Posts extends Component
{
public $title, $categories, $category_id, $body, $post_id, $search, $img;
public $isOpen = 0;
use WithFileUploads;
use WithPagination;
public function mount()
{
$this->categories = Category::all();
}
public function render()
{
$search = '%' . $this->search . '%';
$posts = Post::where('title', 'LIKE', $search)
->orWhere('body', 'LIKE', $search)
->latest()
->paginate(5);
return view('livewire.posts.posts', ['posts' => $posts])->layout('layouts.app');
}
public function create()
{
$this->resetInputFields();
$this->openModal();
}
public function openModal()
{
$this->isOpen = true;
}
public function closeModal()
{
$this->isOpen = false;
}
private function resetInputFields()
{
$this->category_id = '';
$this->title = '';
$this->body = '';
$this->post_id = '';
}
public function store()
{
$this->validate([
'category_id' => 'required',
'title' => 'required',
'body' => 'required',
'img' => 'image|max:1024'
]);
Post::updateOrCreate(
['id' => $this->post_id],
['category_id' => $this->category_id,
'title' => $this->title,
'body' => $this->body,
'img' => $this->img->hashName(),
]);
if(!empty($this->img)) {
$this->img->store('public/docs');
}
session()->flash('message',
$this->post_id ? 'Пост успешно обновлен.' : 'Пост успешно создан.');
$this->closeModal();
$this->resetInputFields();
}
public function edit($id)
{
$post = Post::findOrFail($id);
$this->category_id = $post->category_id;
$this->post_id = $id;
$this->title = $post->title;
$this->body = $post->body;
$this->img = $post->img;
$this->openModal();
}
public function delete($id)
{
Post::find($id)->delete();
session()->flash('message', 'Пост успешно удален.');
}
}
Will setting a name for select solve the problem?
<select class="form-select" aria-label="Default select example" name="category_id">
<option wire:model="category_id" selected>Выберите категорию</option>
#foreach($categories as $category)
<option value="{{ $category->id }}">
{{ $category->name }}
</option>
#endforeach
#error('category_id') <span class="text-red-500">{{ $message }}</span>#enderror
</select>
Currently it doesn't seems like framework can identify the name for this input
This question already exists:
Laravel - Filtered Export to Excel using Maatwebsites is not working
Closed 3 years ago.
I want to export only filtered data in view blade. I am using Laravel 5.8 and Maatwebsite 3.1 and PHP 7.
Controller
public function userresponseReport(Request $request)
{
$data['title'] = 'User Response';
$userresponses = DB::table('user_response as g')
->select(
//DB::raw('DATE(g.created_at) as created_date'),
DB::raw('g.created_at as created_date'),
'g.msisdn',
'g.game_code',
'g.answer',
'g.answer_code',
'g.Amount_charged',
'g.payment_ref',
'g.status',
'g.user_channel'
)
->orderByRaw('g.created_at DESC');
$start_date = $request->start_date;
$end_date = $request->end_date;
$render=[];
if(isset($request->start_date) && isset($request->end_date))
{
$userresponses=$userresponses->whereBetween('created_at',[$start_date.' 00:00:00',$end_date.' 23:59:59']);
$render['start_date']=$request->start_date;
$render['end_date']=$request->end_date;
}elseif(isset($request->start_date))
{
$userresponses=$userresponses->where('created_at',$request->start_date);
$render['start_date']=$request->start_date;
}
if(isset($request->msisdn))
{
$userresponses=$userresponses->where('msisdn','like','%'.$request->msisdn.'%');
$render['msisdn']=$request->msisdn;
}
if(isset($request->game_code))
{
$userresponses=$userresponses->where('game_code','like','%'.$request->game_code.'%');
$render['game_code']=$request->game_code;
}
if(isset($request->user_channel))
{
$userresponses=$userresponses->where('user_channel','like','%'.$request->user_channel.'%');
$render['user_channel']=$request->user_channel;
}
$userresponses= $userresponses->orderBy('created_at','DESC');
$userresponses= $userresponses->paginate(15);
$userresponses= $userresponses->appends($render);
$data['userresponses'] = $userresponses;
return view('report.userresponseReport',$data);
}
public function exportuserresponse(Request $request)
{
return Excel::download(new UserresponseExport($request), 'userresponse.xlsx');
}
I went through the documentation and applied this:
Export folder: UserresponseExport
class UserresponseExport implements FromCollection, WithHeadings, ShouldAutoSize, WithEvents
{
use Exportable;
protected $request;
public function __construct($request)
{
$this->request = $request;
}
public function collection()
{
$userresponses = UserResponse::where('msisdn', 'like','%'.$this->request->msisdn)
->orWhere('game_code', 'like','%'.$this->request->game_code)
->orWhere('user_channel', 'like','%'.$this->request->user_channel)
->get();
$output = [];
foreach ($userresponses as $userresponse)
{
$output[] = [
$userresponse->created_at,
$userresponse->msisdn,
$userresponse->game_code,
$userresponse->answer,
$userresponse->user_channel,
];
}
return collect($output);
}
public function headings(): array
{
return [
'Date Created',
'MSISDN',
'game_code',
'Answer',
'Channel'
];
}
View
<div class="row" style="margin-bottom: 10px">
{{ Form::model(request(),['method'=>'get']) }}
<div class="col-sm-2">
{{ Form::text('msisdn',null,['class'=>'form-control','placeholder'=>'MSISDN']) }}
</div>
<div class="col-sm-2">
{{ Form::text('game_code',null,['class'=>'form-control','placeholder'=>'Game Code']) }}
</div>
<div class="col-sm-2">
{{ Form::text('user_channel',null,['class'=>'form-control','placeholder'=>'Channel']) }}
</div>
<div class="col-sm-2">
{{ Form::date('start_date',null,['class'=>'form-control','placeholder'=>'Date']) }}
</div>
<div class="col-sm-2">
{{ Form::date('end_date',null,['class'=>'form-control','placeholder'=>'Date']) }}
</div>
<div class="col-xs-2">
{{ Form::submit('Search',['class'=>'btn btn-warning']) }}
<i class="fa fa-file-excel-o"></i> Excel
</div>
{{ Form::close() }}
</div>
IThe export submit button is sending everything to Excel. How do I make it to send only the filtered data. Thanks
Update your UserresponseExport, follow this formate,
class UsersExport implements FromCollection, WithHeadings
{
use Exportable;
protected $request;
public function __construct($request)
{
$this->request = $request;
}
public function collection()
{
$users = User::where('name', 'like','%'.$this->request->name)->get();
$output = [];
foreach ($users as $user)
{
$output[] = [
$user->name,
];
}
return collect($output);
}
public function headings(): array
{
return [
'Name',
];
}
}
Make sure your query is corrct, check your query properly.
hello i have this error : ReflectionException Class App\User does not exist Previous exceptions syntax error, unexpected '{', expecting ')' (0)
but dont understand where is syntax error ,
User.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'username', 'nom', 'prenom', 'adresse', 'ville', 'codepostale', 'datedenaissance','email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
protected static function boot()
{
parent::boot();
static::created(function ($user {
$user->profile()->create([
'title' => 'Profil de' . $user->username
]);
});
}
public function getRouteKeyName()
{
return 'username';
}
public function profile()
{
return $this->hasOne('App\Profile');
}
public function posts()
{
return $this->hasMany('App\Post')->orderBy('created_at', 'DESC');
}
}
ProfileController.php
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
class ProfileController extends Controller
{
public function show(User $user)
{
return view('profile.show', compact('user'));
}
public function edit(User $user)
{
$this->authorize('update', $user->profile);
return view('profile.edit', compact('user'));
}
public function update(User $user)
{
$this->authorize('update', $user->profile);
$data = request()->validate([
'title' => 'required',
'description' => 'required',
'image' => 'sometimes|image|max:3000'
]);
if (request('image')) {
$imagePath = request('image')->store('avatars', 'public');
$image = Image::make(public_path("/storage/{$imagePath}"))->fit(800, 800);
$image->save();
auth()->user()->profile->update(array_merge($data,
['image' => $imagePath]
));
} else {
auth()->user()->profile->update($data);
}
auth()->user()->profile->update($data);
return redirect()->route('profile.show', ['user' => $user]);
}
}
show.blade.php
<#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-4">
<img src="{{ $user->profile->getImage() }}" class="rounded-circle">
</div>
<div class="col-8">
<div class="d-flex align-items-baseline">
<div class="h4 mr-3 pt-2">{{ $user->username }}</div>
<button class="btn btn-primary">S'abonner</button>
</div>
<div class="d-flex">
<div class="mr-3">{{ $user->posts->count() }} article(s) en vente
</div>
#can('update', $user->profile)
Modifier Profile
#endcan
<div class="mt-3">
<div class="font-weight-bold">
{{ $user->profile->title }}
</div>
<div class="font-weight-bold">
{{ $user->profile->description }}
</div>
</div>
</div>
</div>
<div class="row mt-5">
#foreach ($user->posts as $post)
<div class="col-4">
<img src="{{ asset('storage') . '/' . $post->image }}" class="w-100">
</div>
#endforeach
</div>
</div>
#endsection
Profile.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
protected $fillable = ['title'];
public function user()
{
return $this->belongsTo('App\User');
}
public function getImage()
{
$imagePath = $this->image ?? 'avatars/default.png';
return "/storage/" . $imagePath;
}
}
i try to create profile with upload image, someone can help me with this error?
Your IDE should give you an error in your overridden boot method, so change this:
static::created(function ($user {
$user->profile()->create([
'title' => 'Profil de' . $user->username
]);
});
to this:
static::created(function ($user) {
$user->profile()->create([
'title' => 'Profil de' . $user->username
]);
});
Note the missing ) in your $user param.